上一篇文章对webBench压力测试工具中的Socket.c文件中的代码进行了详细的解析,接下来在这篇文章中我将会对webbench.c文件中的源码进行分析。如果分析过程中什么地方有误,希望大家指出来,谢谢!
webbench.c源码
#include "socket.c" #include <unistd.h> #include <sys/param.h> #include <rpc/types.h> #include <getopt.h> #include <strings.h> #include <time.h> #include <signal.h>//结构体sigaction所在的头文件 /* values */ volatile int timerexpired=0; int speed=0; int failed=0; int bytes=0; /* globals */ int http10=1; /* 0 - http/0.9, 1 - http/1.0, 2 - http/1.1 */ /* Allow: GET, HEAD, OPTIONS, TRACE */ #define METHOD_GET 0 #define METHOD_HEAD 1 #define METHOD_OPTIONS 2 #define METHOD_TRACE 3 #define PROGRAM_VERSION "1.5" int method=METHOD_GET; //默认情况下使用http中的GET方法发送请求。可以在命令行输入使用其他方法,如--head int clients=1; //默认并发数为1,也就是fork出的子进程个数,可以由命令行参数-c指定 int force=0; int force_reload=0; int proxyport=80; //服务的端口号 char *proxyhost=NULL; //目的主机 int benchtime=30; //测试时间 默认为30秒 可由命令行参数-t指定 /* internal */ int mypipe[2]; //建立管道时使用,mypipe[0]是读取管道的文件描述符,mypipe[1]是向管道中写的文件描述符 char host[MAXHOSTNAMELEN]; //定义服务器IP #define REQUEST_SIZE 2048 char request[REQUEST_SIZE]; //存放一个HTTP请求的信息,默认情况下使用请求GET方法
webben.c文件中包含以下函数:static const struct option long_options[]=//由结构体option构成的数组 { {"force",no_argument,&force,1}, {"reload",no_argument,&force_reload,1}, {"time",required_argument,NULL,'t'}, {"help",no_argument,NULL,'?'}, {"http09",no_argument,NULL,'9'}, {"http10",no_argument,NULL,'1'}, {"http11",no_argument,NULL,'2'}, {"get",no_argument,&method,METHOD_GET}, {"head",no_argument,&method,METHOD_HEAD}, {"options",no_argument,&method,METHOD_OPTIONS}, {"trace",no_argument,&method,METHOD_TRACE}, {"version",no_argument,NULL,'V'}, {"proxy",required_argument,NULL,'p'}, {"clients",required_argument,NULL,'c'}, {NULL,0,NULL,0} };
main函数为程序入口函数,我们从main开始分析代码:(1)int main(int argc, char *argv[]); (2)void usage(); (3)static void build_request(const char *url); (4)static int bench(void); (5)int Socket(const char *host, int clientPort); (6)static void benchcore(const char* host,const int port, const char *request); (7)static void alarm_handler(int signal);
(1)main函数
mian函数的功能是对命令行参数进行解析,如果命令行输入错误,调用usage函数提示用户输入;如果正确,根据解析结果调用build_request函数建立一个http请求。然后调用bench函数进行测试。int main(int argc, char *argv[]) { int opt=0; int options_index=0; char *tmp=NULL; if(argc==1)//仅仅输入一个参数时 { usage();//命令行提示 return 2; } //使用getopt_long函数对命令行参数进行解析,初始化配置 while((opt = getopt_long(argc,argv,"912Vfrt:p:c:?h",long_options,&options_index)) != EOF ) { switch(opt) { case 0 : break; case 'f': force=1;break; case 'r': force_reload=1;break; case '9': http10=0;break; case '1': http10=1;break; case '2': http10=2;break; case 'V': printf(PROGRAM_VERSION"\n");exit(0); case 't': benchtime=atoi(optarg);break; case 'p': /* proxy server parsing server:port */ tmp=strrchr(optarg,':');//strrchr(char *str, char c)找出 str 中最后一次出现的字符 c 的地址,然后将该地址返回。 proxyhost=optarg; if(tmp==NULL) { break; } if(tmp==optarg) { fprintf(stderr,"Error in option --proxy %s: Missing hostname.\n",optarg); return 2; } if(tmp==optarg+strlen(optarg)-1) { fprintf(stderr,"Error in option --proxy %s Port number is missing.\n",optarg); return 2; } *tmp='\0'; proxyport=atoi(tmp+1);break; case ':': case 'h': case '?': usage();return 2;break; case 'c': clients=atoi(optarg);break; } } if(optind==argc) {//命令行输入错误,会使用usage函数来提示用户正确的输入方法 fprintf(stderr,"webbench: Missing URL!\n"); usage(); return 2; } if(clients==0) clients=1; if(benchtime==0) benchtime=30; /* Copyright */ fprintf(stderr,"Webbench - Simple Web Benchmark "PROGRAM_VERSION"\n" "Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.\n" ); //根据用户的输入的url,构造http请求报文放入全局变量request中(request) build_request(argv[optind]);//(argv[optind]是命令行参数的最后一个参数,是目的主机的url) printf("Runing info: "); if(clients==1) printf("1 client"); else printf("%d clients",clients); printf(", running %d sec", benchtime); if(force) printf(", early socket close"); if(proxyhost!=NULL) printf(", via proxy server %s:%d",proxyhost,proxyport); if(force_reload) printf(", forcing reload"); printf(".\n"); return bench(); }
(2)usage函数
/*运行改程序时,如果输入错误的提示*/ static void usage(void) { fprintf(stderr, "webbench [option]... URL\n" " -f|--force Don't wait for reply from server.\n" " -r|--reload Send reload request - Pragma: no-cache.\n" " -t|--time <sec> Run benchmark for <sec> seconds. Default 30.\n" " -p|--proxy <server:port> Use proxy server for request.\n" " -c|--clients <n> Run <n> HTTP clients at once. Default one.\n" " -9|--http09 Use HTTP/0.9 style requests.\n" " -1|--http10 Use HTTP/1.0 protocol.\n" " -2|--http11 Use HTTP/1.1 protocol.\n" " --get Use GET request method.\n" " --head Use HEAD request method.\n" " --options Use OPTIONS request method.\n" " --trace Use TRACE request method.\n" " -?|-h|--help This information.\n" " -V|--version Display program version.\n" ); }
(3)build_request函数
根据参数行命令建立一个Http请求,并将http请求放入到全局数据request中。/*根据url创建一个http请求,将请求放入全局变量char request[REQUEST_SIZE]*/ void build_request(const char *url) { char tmp[10]; int i; //bzero(host,MAXHOSTNAMELEN); //bzero(request,REQUEST_SIZE); memset(host,0,MAXHOSTNAMELEN); memset(request,0,REQUEST_SIZE); if(force_reload && proxyhost != NULL && http10<1) http10=1; if(method==METHOD_HEAD && http10<1) http10=1; if(method==METHOD_OPTIONS && http10<2) http10=2; if(method==METHOD_TRACE && http10<2) http10=2; switch(method)//method是所要创建的http请求的类型,GET,PUSH,POST,HEAD,TRACE { default: case METHOD_GET: strcpy(request,"GET");break; case METHOD_HEAD: strcpy(request,"HEAD");break; case METHOD_OPTIONS: strcpy(request,"OPTIONS");break; case METHOD_TRACE: strcpy(request,"TRACE");break; } strcat(request," "); if(NULL==strstr(url,"://")) { fprintf(stderr, "\n%s: is not a valid URL.\n",url); exit(2); } if(strlen(url)>1500) { fprintf(stderr,"URL is too long.\n"); exit(2); } if (0!=strncasecmp("http://",url,7)) { fprintf(stderr,"\nOnly HTTP protocol is directly supported, set --proxy for others.\n"); exit(2); } /* protocol/host delimiter */ i=strstr(url,"://")-url+3; if(strchr(url+i,'/')==NULL) { fprintf(stderr,"\nInvalid URL syntax - hostname don't ends with '/'.\n"); exit(2); } if(proxyhost==NULL) { /* get port from hostname */ if(index(url+i,':')!=NULL && index(url+i,':')<index(url+i,'/')) { strncpy(host,url+i,strchr(url+i,':')-url-i); //bzero(tmp,10); memset(tmp,0,10); strncpy(tmp,index(url+i,':')+1,strchr(url+i,'/')-index(url+i,':')-1); /* printf("tmp=%s\n",tmp); */ proxyport=atoi(tmp); if(proxyport==0) proxyport=80;//设定端口号 } else { strncpy(host,url+i,strcspn(url+i,"/")); } // printf("Host=%s\n",host); strcat(request+strlen(request),url+i+strcspn(url+i,"/")); } else { // printf("ProxyHost=%s\nProxyPort=%d\n",proxyhost,proxyport); strcat(request,url); } if(http10==1) strcat(request," HTTP/1.0"); else if (http10==2) strcat(request," HTTP/1.1"); strcat(request,"\r\n"); if(http10>0) strcat(request,"User-Agent: WebBench "PROGRAM_VERSION"\r\n"); if(proxyhost==NULL && http10>0) { strcat(request,"Host: "); strcat(request,host); strcat(request,"\r\n"); } if(force_reload && proxyhost!=NULL) { strcat(request,"Pragma: no-cache\r\n"); } if(http10>1) strcat(request,"Connection: close\r\n"); /* add empty line at end */ if(http10>0) strcat(request,"\r\n"); printf("\nRequest:\n%s\n",request); }
(4)bench函数
/*(1)首先测试TCP连接是否合法; (2)调用pipe建立管道; (3)调用fork创建子进程(父子进程共享文件),对每个子进程调用benchcore函数; (4)将每个子进程的测试数据写入到管道中; (5)父进程读取管道中的内容,并做汇总; */ static int bench(void) { int i,j,k; pid_t pid=0;//进程描述符 FILE *f; /*创建一个TCP连接,然后立马用close关闭该连接。只是用于测试是否可以正常建立连接到目的主机*/ i=Socket(proxyhost == NULL ? host : proxyhost, proxyport);//建立TCP连接 if(i<0) { //连接建立失败 fprintf(stderr,"\nConnect to server failed. Aborting benchmark.\n"); return 1; } close(i);//关闭该文件 /*创建管道*/ if(pipe(mypipe)) { perror("pipe failed."); return 3; } /* 使用fork系统调用创建子进程,父进程和子进程是共享文件的,因此他们共享同一个管道*/ for(i=0;i<clients;i++) { pid=fork(); if(pid <= (pid_t) 0)//说明是在子进程中或者创建进程出错了 { sleep(1); /* make childs faster */ break; } } if( pid < (pid_t) 0)//创建子进程失败 { fprintf(stderr,"problems forking worker no. %d\n",i); perror("fork failed."); return 3; } //在每个子进程中调用benchcore函数,创建TCP连接,将数据写入管道中 if(pid == (pid_t) 0) { if(proxyhost == NULL) benchcore(host,proxyport,request);//对每个子进程进行测试 else benchcore(proxyhost,proxyport,request); /* write results to pipe */ f=fdopen(mypipe[1],"w");//只用于打开管道,返回一个文件描述符 if(f==NULL) { perror("open pipe for writing failed."); return 3; } fprintf(f,"%d %d %d\n",speed,failed,bytes);//往管道中写数据 fclose(f); return 0; } else//父进程读取管道中的内容 { f=fdopen(mypipe[0],"r");//打开管道,并返回一个标示读取的文件句柄 if(f==NULL) { perror("open pipe for reading failed."); return 3; } setvbuf(f,NULL,_IONBF,0); speed=0; failed=0; bytes=0; while(1) { pid=fscanf(f,"%d %d %d",&i,&j,&k);//从f标示文件描述符中读取数据 if(pid<2) { fprintf(stderr,"Some of our childrens died.\n"); break; } //将从管道中读取的数据统计到全局变量中 speed+=i; failed+=j; bytes+=k; /* fprintf(stderr,"*Knock* %d %d read=%d\n",speed,failed,pid); */ if(--clients==0) break; } fclose(f); printf("\nSpeed=%d pages/min, %d bytes/sec.\nRequests: %d susceed, %d failed.\n", (int)((speed+failed)/(benchtime/60.0f)), (int)(bytes/(float)benchtime), speed, failed); } return i; }
(5)benchcore函数/*对http请求进行测试*/ void benchcore(const char *host,const int port,const char *req) { int rlen; char buf[1500]; int s,i; struct sigaction sa; /* setup alarm signal handler */ sa.sa_handler = alarm_handler; sa.sa_flags=0; if(sigaction(SIGALRM,&sa,NULL)) { exit(3); } alarm(benchtime); // after benchtime,then exit rlen=strlen(req); nexttry:while(1) { if(timerexpired)//超时 { if(failed>0) { /* fprintf(stderr,"Correcting failed by signal\n"); */ failed--; } return; } s=Socket(host,port);//使用host和port建立tcp连接 if(s<0) { failed++;continue;} //连接失败 if(rlen!=write(s,req,rlen)) { failed++; close(s); continue; }//将请求写入到套接字描述符所指代的socket中 if(http10==0) { if(shutdown(s,1)) { failed++ ;close(s); continue; } } if(force==0) //说明要等待服务器的响应 { /* read all available data from socket */ while(1) { if(timerexpired) break; i=read(s,buf,1500); /* fprintf(stderr,"%d\n",i); */ if(i<0) { failed++; close(s); goto nexttry; } else if(i==0) break; else bytes+=i; } } if(close(s)) {failed++;continue;}//关闭socket speed++; } }
(6)alarm_handler函数static void alarm_handler(int signal) { timerexpired=1; }