zoukankan      html  css  js  c++  java
  • 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指向的数据的值。

    [cpp] view plaincopy
     
    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的下标值。

    例如对于

    [cpp] view plaincopy
     
    1. while ( (opt = getopt_long(argc, argv, optstring, long_options, &option_index)) != -1)    
    2.    {    
    3.         printf("opt = %c ", opt);           //被指定的参数名称(即该字母)  
    4.         printf("optarg = %s ", optarg);     //optarg为参数的指定值  
    5.         printf("optind = %d ", optind);          //下一个将被处理到的参数在argv中的下标值。  
    6.         printf("argv[optind - 1] = %s ",  argv[optind - 1]);    
    7.         printf("option_index = %d ", 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通信所要发送的报文。

    [cpp] view plaincopy
     
    1. void build_request(const char *url)  
    2. {  
    3.   char tmp[10];  
    4.   int i;  
    5.   
    6.   bzero(host,MAXHOSTNAMELEN);    //置host字符串前MAXHOSTNAMELEN个字节为零且包括‘’。  
    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, " %s: is not a valid URL. ",url);  
    28.       exit(2);  
    29.   }  
    30.   if(strlen(url)>1500)  
    31.   {  
    32.          fprintf(stderr,"URL is too long. ");  
    33.      exit(2);  
    34.   }  
    35.   if(proxyhost==NULL)  
    36.        if (0!=strncasecmp("http://",url,7))   
    37.        {   
    38.              fprintf(stderr," Only HTTP protocol is directly supported, set --proxy for others. ");  
    39.              exit(2);  
    40.            }  
    41.   /* protocol/host delimiter */  
    42.   i=strstr(url,"://")-url+3;                              //找到url中:'//'的出现的位置  
    43.   /* printf("%d ",i); */  
    44.   
    45.   if(strchr(url+i,'/')==NULL) {                                                                                     //判断url中除去http://后是否存在'/'  
    46.             fprintf(stderr," Invalid URL syntax - hostname don't ends with '/'. ");  
    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 ",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 ",host);  
    67.    strcat(request+strlen(request),url+i+strcspn(url+i,"/"));  
    68.   } else  
    69.   {  
    70.    // printf("ProxyHost=%s ProxyPort=%d ",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," ");  
    78.   if(http10>0)  
    79.       strcat(request,"User-Agent: WebBench "PROGRAM_VERSION" ");  
    80.   if(proxyhost==NULL && http10>0)  
    81.   {  
    82.       strcat(request,"Host: ");  
    83.       strcat(request,host);  
    84.       strcat(request," ");  
    85.   }  
    86.   if(force_reload && proxyhost!=NULL)  
    87.   {  
    88.       strcat(request,"Pragma: no-cache ");  
    89.   }  
    90.   if(http10>1)  
    91.       strcat(request,"Connection: close ");  
    92.   /* add empty line at end */  
    93.   if(http10>0) strcat(request," ");   
    94.   // printf("Req=%s ",request);  
    95. }  



    三、bench函数  
    该函数主要采用fork出子进程来测试网站,并且利用主进程来读取所有子进程写入的数据,每个子进程调用benchcore函数来测试存到全局变量speed faulted,
    最后主进程汇总各个子线程的数据显示出来~

    [cpp] view plaincopy
     
    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," Connect to server failed. Aborting benchmark. ");  
    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 ",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 ",speed,failed); */  
    67.      fprintf(f,"%d %d %d ",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. ");  
    91.                        break;  
    92.                   }  
    93.           speed+=i;  
    94.           failed+=j;  
    95.           bytes+=k;  
    96.           /* fprintf(stderr,"*Knock* %d %d read=%d ",speed,failed,pid); */  
    97.           if(--clients==0) break;            //当读取完所有子进程写入的结果后 主进程结束  
    98.       }  
    99.       fclose(f);  
    100.   
    101.   printf(" Speed=%d pages/min, %d bytes/sec. Requests: %d susceed, %d failed. ",  
    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定义如下:

    [cpp] view plaincopy
     
    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标志。

    [cpp] view plaincopy
     
      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 "); */  
      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 ",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. }  
  • 相关阅读:
    积累
    AnkhSVN使用记录
    时间戳
    Nhibernate
    Css的sb问题
    ajax
    WAS资料收集
    CryStal资料收集
    Decorator模式
    MSDN WebCast网络广播全部下载列表
  • 原文地址:https://www.cnblogs.com/yuankaituo/p/4274796.html
Copyright © 2011-2022 走看看