Webbench
Webbench是一個在linux下使用的非常簡單的網站壓測工具。它使用fork()模擬多個客戶端同時訪問我們設定的URL,測試網站在壓力下工作的性能,最多可以模擬3萬個併發連接去測試網站的負載能力。Webbench使用C語言編寫, 代碼實在太簡潔,源碼加起來不到600行。整個源碼分析主要的分析都被我加在了代碼的後面中文註釋中,歡迎討論~
webbench壓測的命令:
webbench -c 300 -t 10 url
其中:-c 300 表示併發數(可以了理解成客戶端),
-t 10表示時間(秒)
url 想要壓測的url
下載鏈接:http://home.tiscali.cz/~cz210552/webbench.html
整個代碼的流程圖如下:
一、首先我們從主函數入手,前面幾個都是初始化變量,沒什麼好說的,出現了一個getopt_long函數,應該有些人沒有用過這個函數,我先來分析下這個函數吧~
int getopt_long(int argc, char * const argv[],const char *optstring,const struct option *longopts, int *longindex);
1、前兩個參數,就是main函數的argc和argv,這兩者直接傳入即可,
2、optstring的格式舉例說明比較方便,例如:char *optstring = "abcd:";
上面這個optstring在傳入之後,getopt函數將依次檢查命令行是否指定了 -a, -b, -c及 -d,(這需要多次調用getopt函數,直到其返回-1),當檢查到上面某一個參數被指定時,函數會返回被指定的參數名稱(即該字母),最後一個參數d後面帶有冒號,: 表示參數d是可以指定值的,如 -d 100 或 -d user。
3、longopts指向的是一個由option結構體組成的數組,那個數組的每個元素,指明瞭一個“長參數”(即形如--name的參數)名稱和性質:
struct option {
const char *name;
int has_arg;
int *flag;
int val;
};
name 是參數的名稱
has_arg 指明是否帶參數值,其數值可選:
no_argument (即 0) 表明這個長參數不帶參數(即不帶數值,如:--name)
required_argument (即 1) 表明這個長參數必須帶參數(即必須帶數值,如:--name Bob)
optional_argument(即2)表明這個長參數後面帶的參數是可選的,(即--name和--name Bob均可)
flag 當這個指針爲空的時候,函數直接將val的數值從getopt_long的返回值返回出去,當它非空時,val的值會被賦到flag指向的整型數中,而函數返回值爲0
val 用於指定函數找到該選項時的返回值,或者當flag非空時指定flag指向的數據的值。
- static const struct option long_options[]=
- {
- {"force",no_argument,&force,1},
- {"reload",no_argument,&force_reload,1},
- {"time",required_argument,NULL,'t'}, //bench的測試時間 默認爲30s
- {"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}
- };
例如對於
- while ( (opt = getopt_long(argc, argv, optstring, long_options, &option_index)) != -1)
- {
- printf("opt = %c\n", opt); //被指定的參數名稱(即該字母)
- printf("optarg = %s\n", optarg); //optarg爲參數的指定值
- printf("optind = %d\n", optind); //下一個將被處理到的參數在argv中的下標值。
- printf("argv[optind - 1] = %s\n", argv[optind - 1]);
- printf("option_index = %d\n", option_index); //它指向的變量將記錄當前找到參數符合longopts裏的第幾個元素的描述,即是longopts的下標值。
- }
輸入命令行test_getopt_long -reqarg 100
輸出:
opt = reqarg
optarg = 100
optind = 3
argv[optind - 1] = 100
二、build_request函數
目的是對url進行處理,得到host,proxyport,request
其中request就是之後利用socket與host通信所要發送的報文。
- void build_request(const char *url)
- {
- char tmp[10];
- int i;
- bzero(host,MAXHOSTNAMELEN); //置host字符串前MAXHOSTNAMELEN個字節爲零且包括‘\0’。
- bzero(request,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)
- {
- 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(proxyhost==NULL)
- 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; //找到url中:'//'的出現的位置
- /* printf("%d\n",i); */
- if(strchr(url+i,'/')==NULL) { //判斷url中除去http://後是否存在'/'
- fprintf(stderr,"\nInvalid URL syntax - hostname don't ends with '/'.\n");
- exit(2);
- }
- if(proxyhost==NULL) //if裏面都是爲了獲取端口號 主機名 和 request
- { //比如url="http://localhost:12345/test"; //if運行結束後 proxyport=12345,host=localhost
- /* get port from hostname */
- if(index(url+i,':')!=NULL &&
- index(url+i,':')<index(url+i,'/'))
- {
- strncpy(host,url+i,strchr(url+i,':')-url-i); //char *strncpy(char *destin, char *source, int
- //maxlen),把src所指由NULL結束的字符串的前n個字節複製到dest所指的數組中。
- bzero(tmp,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("Req=%s\n",request);
- }
三、bench函數
該函數主要採用fork出子進程來測試網站,並且利用主進程來讀取所有子進程寫入的數據,每個子進程調用benchcore函數來測試存到全局變量speed faulted,
最後主進程彙總各個子線程的數據顯示出來~
- /* vraci system rc error kod */
- static int bench(void)
- {
- int i,j,k;
- pid_t pid=0;
- FILE *f;
- /* check avaibility of target server */
- i=Socket(proxyhost==NULL?host:proxyhost,proxyport); //測試網站是否能連
- if(i<0) {
- fprintf(stderr,"\nConnect to server failed. Aborting benchmark.\n");
- return 1;
- }
- close(i);
- /* create pipe */
- if(pipe(mypipe))
- {
- perror("pipe failed.");
- return 3;
- }
- /* not needed, since we have alarm() in childrens */
- /* wait 4 next system clock tick */
- /*
- cas=time(NULL);
- while(time(NULL)==cas)
- sched_yield();
- */
- /* fork childs */
- for(i=0;i<clients;i++)
- {
- pid=fork(); // 1)在父進程中,fork返回新創建子進程的進程ID;
- //2)在子進程中,fork返回0;
- // 3)如果出現錯誤,fork返回一個負值;
- if(pid <= (pid_t) 0)
- {
- /* child process or error*/
- 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;
- }
- if(pid== (pid_t) 0)
- {
- /* I am a child */
- if(proxyhost==NULL)
- benchcore(host,proxyport,request); //bench的核心代碼 子進程進入此函數測試網站,直到benchtime耗完爲止
- 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(stderr,"Child - %d %d\n",speed,failed); */
- fprintf(f,"%d %d %d\n",speed,failed,bytes); //各個子進程往pipe中寫入測試結果
- 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); //setvbuf 就是設置文件流的buffer配置,如setvbuf(input, bufr, _IOFBF, 512)是設置 input這個文件流使用 bufr
- //所指的512個字節作爲 input文件的buffer, 當你操作input文件時,數據都會暫存在 bufr
- //裏面,每次讀input時,系統會一次性讀512字節到bufr裏暫存。
- speed=0;
- failed=0;
- bytes=0;
- while(1)
- {
- pid=fscanf(f,"%d %d %d",&i,&j,&k); //主進程從pipe中讀取每個子進程寫的數據分別讀取到i,j,k中,由於pipe在空時,會被阻塞
- 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;
- }
四、benchcore函數
該函數主要採用socket連接、發送request、接收來測試網站,測試結果存在全局變量speed faulted,bytes
定時時間結束則退出函數~
其中關於sigaction函數的使用:
int sigaction(int signo,const struct sigaction *restrict act,struct sigaction *restrict oact);
其中signo的信息可參考:http://blog.csdn.net/liucimin/article/details/40507443
其中結構sigaction定義如下:
- struct sigaction{
- void (*sa_handler)(int);
- sigset_t sa_mask;
- int sa_flag;
- void (*sa_sigaction)(int,siginfo_t *,void *);
- };
sa_handler字段包含一個信號捕捉函數的地址
sa_flag標誌。
- 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 */ //設定定時器,該進程benchtime之後結束測試
- sa.sa_handler=alarm_handler;
- sa.sa_flags=0;
- if(sigaction(SIGALRM,&sa,NULL)) //通過信號設置時間結束後全局變量timerexpired的值
- exit(3);
- alarm(benchtime); //alarm也稱爲鬧鐘函數,它可以在進程中設置一個定時器,當定時器指定的時間到時
- //,它向進程發送SIGALRM信號。如果忽略或者不捕獲此信號
- //,則其默認動作是終止調用該alarm函數的進程。
- rlen=strlen(req);
- nexttry:while(1)
- {
- if(timerexpired) //到點後結束函數
- {
- if(failed>0)
- {
- /* fprintf(stderr,"Correcting failed by signal\n"); */
- failed--;
- }
- return;
- }
- s=Socket(host,port); //Socket是頭文件中自己寫的函數,返回socket連接後的結果
- if(s<0) { failed++;continue;}
- if(rlen!=write(s,req,rlen)) {failed++;close(s);continue;} //往服務器發request
- 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); //成功返回讀取的字節數,出錯返回-1並設置errno,如果在調read之前已到達文件末尾,則這次read返回0
- /* fprintf(stderr,"%d\n",i); */
- if(i<0) //讀取失敗 failed++,重新發送request讀數據
- {
- failed++;
- close(s);
- goto nexttry;
- }
- else
- if(i==0) break;
- else
- bytes+=i;
- }
- }
- if(close(s)) {failed++;continue;}
- speed++;
- }
- }