最值得關注的10個C開源項目之Webbench源碼分析

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指向的數據的值。

  1. static const struct option long_options[]=  
  2. {  
  3.  {"force",no_argument,&force,1},  
  4.  {"reload",no_argument,&force_reload,1},  
  5.  {"time",required_argument,NULL,'t'},               //bench的測試時間 默認爲30s  
  6.  {"help",no_argument,NULL,'?'},  
  7.  {"http09",no_argument,NULL,'9'},  
  8.  {"http10",no_argument,NULL,'1'},  
  9.  {"http11",no_argument,NULL,'2'},  
  10.  {"get",no_argument,&method,METHOD_GET},  
  11.  {"head",no_argument,&method,METHOD_HEAD},  
  12.  {"options",no_argument,&method,METHOD_OPTIONS},  
  13.  {"trace",no_argument,&method,METHOD_TRACE},  
  14.  {"version",no_argument,NULL,'V'},  
  15.  {"proxy",required_argument,NULL,'p'},  
  16.  {"clients",required_argument,NULL,'c'},  
  17.  {NULL,0,NULL,0}  
  18. };  
4、option_index指向的變量將記錄當前找到參數符合longopts裏的第幾個元素的描述,即是longopts的下標值。

例如對於

  1. while ( (opt = getopt_long(argc, argv, optstring, long_options, &option_index)) != -1)    
  2.    {    
  3.         printf("opt = %c\n", opt);           //被指定的參數名稱(即該字母)  
  4.         printf("optarg = %s\n", optarg);     //optarg爲參數的指定值  
  5.         printf("optind = %d\n", optind);          //下一個將被處理到的參數在argv中的下標值。  
  6.         printf("argv[optind - 1] = %s\n",  argv[optind - 1]);    
  7.         printf("option_index = %d\n", option_index);          //它指向的變量將記錄當前找到參數符合longopts裏的第幾個元素的描述,即是longopts的下標值。  
  8.    }    


輸入命令行test_getopt_long  -reqarg 100

輸出:
opt = reqarg 
optarg = 100  
optind = 3  
argv[optind - 1] = 100  


二、build_request函數
目的是對url進行處理,得到host,proxyport,request
其中request就是之後利用socket與host通信所要發送的報文。

  1. void build_request(const char *url)  
  2. {  
  3.   char tmp[10];  
  4.   int i;  
  5.   
  6.   bzero(host,MAXHOSTNAMELEN);    //置host字符串前MAXHOSTNAMELEN個字節爲零且包括‘\0’。  
  7.   bzero(request,REQUEST_SIZE);  
  8.   
  9.   if(force_reload && proxyhost!=NULL && http10<1) http10=1;  
  10.   if(method==METHOD_HEAD && http10<1) http10=1;  
  11.   if(method==METHOD_OPTIONS && http10<2) http10=2;  
  12.   if(method==METHOD_TRACE && http10<2) http10=2;  
  13.   
  14.   switch(method)  
  15.   {  
  16.       default:  
  17.       case METHOD_GET: strcpy(request,"GET");break;  
  18.       case METHOD_HEAD: strcpy(request,"HEAD");break;  
  19.       case METHOD_OPTIONS: strcpy(request,"OPTIONS");break;  
  20.       case METHOD_TRACE: strcpy(request,"TRACE");break;  
  21.   }  
  22.             
  23.   strcat(request," ");  
  24.   
  25.   if(NULL==strstr(url,"://"))  
  26.   {  
  27.       fprintf(stderr, "\n%s: is not a valid URL.\n",url);  
  28.       exit(2);  
  29.   }  
  30.   if(strlen(url)>1500)  
  31.   {  
  32.          fprintf(stderr,"URL is too long.\n");  
  33.      exit(2);  
  34.   }  
  35.   if(proxyhost==NULL)  
  36.        if (0!=strncasecmp("http://",url,7))   
  37.        {   
  38.              fprintf(stderr,"\nOnly HTTP protocol is directly supported, set --proxy for others.\n");  
  39.              exit(2);  
  40.            }  
  41.   /* protocol/host delimiter */  
  42.   i=strstr(url,"://")-url+3;                              //找到url中:'//'的出現的位置  
  43.   /* printf("%d\n",i); */  
  44.   
  45.   if(strchr(url+i,'/')==NULL) {                                                                                     //判斷url中除去http://後是否存在'/'  
  46.             fprintf(stderr,"\nInvalid URL syntax - hostname don't ends with '/'.\n");  
  47.             exit(2);  
  48.                               }  
  49.   if(proxyhost==NULL)                                                                                       //if裏面都是爲了獲取端口號 主機名 和 request  
  50.   {                                                                                                         //比如url="http://localhost:12345/test";                                                                              //if運行結束後 proxyport=12345,host=localhost  
  51.    /* get port from hostname */  
  52.    if(index(url+i,':')!=NULL &&  
  53.       index(url+i,':')<index(url+i,'/'))                                                   
  54.    {  
  55.        strncpy(host,url+i,strchr(url+i,':')-url-i);        //char *strncpy(char *destin, char *source, int                            
  56.                                   //maxlen),把src所指由NULL結束的字符串的前n個字節複製到dest所指的數組中。  
  57.        bzero(tmp,10);  
  58.        strncpy(tmp,index(url+i,':')+1,strchr(url+i,'/')-index(url+i,':')-1);  
  59.        /* printf("tmp=%s\n",tmp); */  
  60.        proxyport=atoi(tmp);  
  61.        if(proxyport==0) proxyport=80;  
  62.    } else  
  63.    {  
  64.      strncpy(host,url+i,strcspn(url+i,"/"));  
  65.    }  
  66.    // printf("Host=%s\n",host);  
  67.    strcat(request+strlen(request),url+i+strcspn(url+i,"/"));  
  68.   } else  
  69.   {  
  70.    // printf("ProxyHost=%s\nProxyPort=%d\n",proxyhost,proxyport);  
  71.    strcat(request,url);  
  72.   }  
  73.   if(http10==1)  
  74.       strcat(request," HTTP/1.0");  
  75.   else if (http10==2)  
  76.       strcat(request," HTTP/1.1");  
  77.   strcat(request,"\r\n");  
  78.   if(http10>0)  
  79.       strcat(request,"User-Agent: WebBench "PROGRAM_VERSION"\r\n");  
  80.   if(proxyhost==NULL && http10>0)  
  81.   {  
  82.       strcat(request,"Host: ");  
  83.       strcat(request,host);  
  84.       strcat(request,"\r\n");  
  85.   }  
  86.   if(force_reload && proxyhost!=NULL)  
  87.   {  
  88.       strcat(request,"Pragma: no-cache\r\n");  
  89.   }  
  90.   if(http10>1)  
  91.       strcat(request,"Connection: close\r\n");  
  92.   /* add empty line at end */  
  93.   if(http10>0) strcat(request,"\r\n");   
  94.   // printf("Req=%s\n",request);  
  95. }  


三、bench函數  
該函數主要採用fork出子進程來測試網站,並且利用主進程來讀取所有子進程寫入的數據,每個子進程調用benchcore函數來測試存到全局變量speed faulted,
最後主進程彙總各個子線程的數據顯示出來~

  1. /* vraci system rc error kod */  
  2. static int bench(void)  
  3. {  
  4.   int i,j,k;      
  5.   pid_t pid=0;  
  6.   FILE *f;  
  7.   
  8.   /* check avaibility of target server */  
  9.   i=Socket(proxyhost==NULL?host:proxyhost,proxyport);       //測試網站是否能連  
  10.   if(i<0) {   
  11.        fprintf(stderr,"\nConnect to server failed. Aborting benchmark.\n");  
  12.            return 1;  
  13.          }  
  14.   close(i);  
  15.   /* create pipe */  
  16.   if(pipe(mypipe))  
  17.   {  
  18.       perror("pipe failed.");  
  19.       return 3;  
  20.   }  
  21.   
  22.   /* not needed, since we have alarm() in childrens */  
  23.   /* wait 4 next system clock tick */  
  24.   /* 
  25.   cas=time(NULL); 
  26.   while(time(NULL)==cas) 
  27.         sched_yield(); 
  28.   */  
  29.   
  30.   /* fork childs */  
  31.   for(i=0;i<clients;i++)  
  32.   {  
  33.        pid=fork();     // 1)在父進程中,fork返回新創建子進程的進程ID;  
  34.                       //2)在子進程中,fork返回0;  
  35.                       //  3)如果出現錯誤,fork返回一個負值;  
  36.        if(pid <= (pid_t) 0)  
  37.        {  
  38.            /* child process or error*/  
  39.                sleep(1); /* make childs faster */  
  40.            break;  
  41.        }  
  42.   }  
  43.   
  44.   if( pid< (pid_t) 0)  
  45.   {  
  46.           fprintf(stderr,"problems forking worker no. %d\n",i);  
  47.       perror("fork failed.");  
  48.       return 3;  
  49.   }  
  50.   
  51.   if(pid== (pid_t) 0)  
  52.   {  
  53.     /* I am a child */  
  54.     if(proxyhost==NULL)  
  55.       benchcore(host,proxyport,request);          //bench的核心代碼 子進程進入此函數測試網站,直到benchtime耗完爲止  
  56.          else  
  57.       benchcore(proxyhost,proxyport,request);  
  58.   
  59.          /* write results to pipe */  
  60.      f=fdopen(mypipe[1],"w");  
  61.      if(f==NULL)  
  62.      {  
  63.          perror("open pipe for writing failed.");  
  64.          return 3;  
  65.      }  
  66.      /* fprintf(stderr,"Child - %d %d\n",speed,failed); */  
  67.      fprintf(f,"%d %d %d\n",speed,failed,bytes);        //各個子進程往pipe中寫入測試結果  
  68.      fclose(f);  
  69.      return 0;  
  70.   } else  
  71.   {  
  72.       f=fdopen(mypipe[0],"r");  
  73.       if(f==NULL)   
  74.       {  
  75.           perror("open pipe for reading failed.");  
  76.           return 3;  
  77.       }  
  78.       setvbuf(f,NULL,_IONBF,0);        //setvbuf 就是設置文件流的buffer配置,如setvbuf(input, bufr, _IOFBF, 512)是設置 input這個文件流使用 bufr   
  79.                       //所指的512個字節作爲 input文件的buffer, 當你操作input文件時,數據都會暫存在 bufr   
  80.                       //裏面,每次讀input時,系統會一次性讀512字節到bufr裏暫存。  
  81.       speed=0;  
  82.           failed=0;  
  83.           bytes=0;  
  84.   
  85.       while(1)  
  86.       {  
  87.           pid=fscanf(f,"%d %d %d",&i,&j,&k);        //主進程從pipe中讀取每個子進程寫的數據分別讀取到i,j,k中,由於pipe在空時,會被阻塞  
  88.           if(pid<2)  
  89.                   {  
  90.                        fprintf(stderr,"Some of our childrens died.\n");  
  91.                        break;  
  92.                   }  
  93.           speed+=i;  
  94.           failed+=j;  
  95.           bytes+=k;  
  96.           /* fprintf(stderr,"*Knock* %d %d read=%d\n",speed,failed,pid); */  
  97.           if(--clients==0) break;            //當讀取完所有子進程寫入的結果後 主進程結束  
  98.       }  
  99.       fclose(f);  
  100.   
  101.   printf("\nSpeed=%d pages/min, %d bytes/sec.\nRequests: %d susceed, %d failed.\n",  
  102.           (int)((speed+failed)/(benchtime/60.0f)),  
  103.           (int)(bytes/(float)benchtime),  
  104.           speed,  
  105.           failed);                              //輸出所有子進程記錄數據之和的結果  
  106.   }  
  107.   return i;  
  108. }  


四、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定義如下:

  1. struct sigaction{  
  2.   void (*sa_handler)(int);  
  3.    sigset_t sa_mask;  
  4.   int sa_flag;  
  5.   void (*sa_sigaction)(int,siginfo_t *,void *);  
  6. };   

sa_handler字段包含一個信號捕捉函數的地址
sa_flag標誌。

  1. void benchcore(const char *host,const int port,const char *req)  
  2. {  
  3.  int rlen;  
  4.  char buf[1500];  
  5.  int s,i;  
  6.    
  7.   
  8.  struct sigaction sa;  
  9.   
  10.  /* setup alarm signal handler */                                      //設定定時器,該進程benchtime之後結束測試  
  11.  sa.sa_handler=alarm_handler;  
  12.  sa.sa_flags=0;  
  13.  if(sigaction(SIGALRM,&sa,NULL))                    //通過信號設置時間結束後全局變量timerexpired的值  
  14.     exit(3);  
  15.  alarm(benchtime);                                  //alarm也稱爲鬧鐘函數,它可以在進程中設置一個定時器,當定時器指定的時間到時  
  16.                                                     //,它向進程發送SIGALRM信號。如果忽略或者不捕獲此信號  
  17.                                                     //,則其默認動作是終止調用該alarm函數的進程。  
  18.   
  19.  rlen=strlen(req);  
  20.  nexttry:while(1)  
  21.  {  
  22.     if(timerexpired)                            //到點後結束函數  
  23.     {  
  24.        if(failed>0)  
  25.        {  
  26.           /* fprintf(stderr,"Correcting failed by signal\n"); */  
  27.           failed--;  
  28.        }  
  29.        return;  
  30.     }  
  31.     s=Socket(host,port);                          //Socket是頭文件中自己寫的函數,返回socket連接後的結果  
  32.     if(s<0) { failed++;continue;}   
  33.     if(rlen!=write(s,req,rlen)) {failed++;close(s);continue;}       //往服務器發request  
  34.     if(http10==0)   
  35.         if(shutdown(s,1)) { failed++;close(s);continue;}  
  36.     if(force==0)                                  
  37.     {  
  38.             /* read all available data from socket */  
  39.         while(1)                                          
  40.         {  
  41.               if(timerexpired) break;   
  42.           i=read(s,buf,1500);                       //成功返回讀取的字節數,出錯返回-1並設置errno,如果在調read之前已到達文件末尾,則這次read返回0  
  43.               /* fprintf(stderr,"%d\n",i); */  
  44.           if(i<0)                          //讀取失敗 failed++,重新發送request讀數據  
  45.               {   
  46.                  failed++;  
  47.                  close(s);  
  48.                  goto nexttry;  
  49.               }  
  50.            else  
  51.                if(i==0) break;           
  52.                else  
  53.                    bytes+=i;  
  54.         }  
  55.     }  
  56.     if(close(s)) {failed++;continue;}  
  57.     speed++;  
  58.  }  
  59. }  


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章