webbench源码分析 学习笔记(转载)

一、简介

Web Bench是一个网站压力测试的工具。其最后更新时间是2004年,已经十年多了。其源代码总共才500多行,全部使用C语言编写,最多可以模拟上万个并发连接。其下载主页为webbench

我自己下载的时候碰到了一个问题,虽然后缀是tar.gz但是似乎并没有用gzip压缩,建议改名将.gz去掉,然后不要添加-z参数,直接用tar解压即可。

源码阅读起来也非常简单,很适合作为刚刚了解Linux及网络编程相关内容的新手。毕竟我也是,有出错的地方也欢迎大家指正。本篇主要是转载了一篇大佬的博客内容,基本差不太多,有些地方加了点内容,主要是自己写一下加深下记忆。想看大佬点这里

首先该源码主要就是webbench.c和sockets.c这两个文件,其他都是一些配置信息和说明文档,可以不用管。

二、主要函数:

1.socket.c主要是用于创建一个socket连接;

2.在webbench.c中主要有以下几个函数:

 //main主函数   
int main(int argc,char *argv[])    
//用于执行命令输入出错时输出的信息,用于提示正确的使用方法
static void usage(void)   
//用来创建http连接请求的,其实就是将具体的请求信息写入一个字符数组中供后续使用
void build_request(const char *url) 
//创建管道和子进程,子进程调用核心函数,同时从管道中获取信息并输出到屏幕。
static int bench(void)
//子进程的核心函数,就是在规定时间内不断的往目的地址送请求并进行测试成功与否
void benchcore(const char *host,const int port,const char *req)  

三、主要工作流程:

1.进入main函数,解析命令行参数;

2.调用build_request()函数,构造http request信息;

3.调用bench()函数,根据client大小fork子进程(参数中并发数量的体现);

4.子进程调用benchcore()函数进行测试,挂接信号处理函数alarm_handler(参数中测试时间的体现),将结果写入管道。

5.主进程从管道读取消息,并输出到stdout。

四、源码及注释:

1.socket.c

/*功能:以网络地址和端口号创建socket连接
 * 创建失败返回-1,成功返回一个sockt描述符*/
int Socket(const char *host, int clientPort)
{
    int sock;
    unsigned long inaddr;
    struct sockaddr_in ad;
    struct hostent *hp;

    memset(&ad, 0, sizeof(ad));
    ad.sin_family = AF_INET;
    inaddr = inet_addr(host);//若字符串有效则将字符串转换为32位二进制网络字节序的IPV4地址,否则为INADDR_NONE;
    if (inaddr != INADDR_NONE)
        memcpy(&ad.sin_addr, &inaddr, sizeof(inaddr));
    else
    {
        hp = gethostbyname(host); //返回对应于给定主机名的包含主机名字和
                   地址信息的hostent结构指针;
        if (hp == NULL)
            return -1;
        memcpy(&ad.sin_addr, hp->h_addr, hp->h_length);
    }
    ad.sin_port = htons(clientPort);//将一个无符号短整型(s)的主机数值(h)转换为网络字节顺序(n);
    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
        return sock;
    if (connect(sock, (struct sockaddr *)&ad, sizeof(ad)) < 0)
        return -1;
    return sock;
}

2.webbench.c
- 全局变量设置

/* volatile:
 *    - 让系统总是从内存读取数据,告诉编译器不要做任何优化,变量会在程序外被改变
 */
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 */ //HTTP协议版本
/* 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
int clients=1; //并发数,即子进程个数,默认为1,可以由命令行参数-c指定
int force=0; //是否等待从服务器获取数据,0表示等待
int force_reload=0; //是否使用cache,0为使用
int proxyport=80; //代理服务器端口,默认为80
char *proxyhost=NULL; //代理服务器IP,默认为NULL
/*
 * 执行时间,默认为30秒,可由命令行参数-t指定,
 * 当子进程执行时间超过这个秒数之后,
 * 发送 SIGALRM 信号,将 timerexpired 设置为 1,
 * 让所有子进程退出 
 */
int benchtime=30; 
/* internal */
int mypipe[2]; //创建管道(半双工),用于父子进程间通信 mypipe[0] 为父进程使用的读管道,mypipe[1]为子进程使用的写管道
char host[MAXHOSTNAMELEN]; //保存服务器IP
#define REQUEST_SIZE 2048
char request[REQUEST_SIZE]; //保存HTTP请求信息

/* 命令行的选项配置表,配合 getopt_long函数使用 */
static const struct option long_options[]={
     {"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}
};
/*struct option {
const char *name;
int has_arg;
int *flag;
int val;
};
struct option结构中的元素解释如下:
1、const char *name:选项名,前面没有短横线。譬如"help"、"verbose"之类。
2、int has_arg:描述长选项是否有选项参数,如果有,是哪种类型的参数,其值见下表 :
符号常量             数值            含义
no_argument            0            选项没有参数
required_argument      1            选项需要参数
optional_argument      2            选项参数是可选的
3、int *flag:
如果该指针为NULL,那么getopt_long返回val字段的值;
如果该指针不为NULL,那么会使得它所指向的结构填入val字段的值,同时getopt_long返回0
4、int val:
如果flag是NULL,那么val通常是个字符常量,如果短选项和长选项一致,
那么该字符就应该与optstring中出现的这个选项的参数相同;*/

- main()函数

int main(int argc, char *argv[])
{
    int opt=0;
    int options_index=0;
    char *tmp=NULL;
    if(argc==1)    //输入参数只有一个时表明输入参数不足
    {
        usage();
        return 2;
    } 

    /* 参数检查,并设置相应选项,参见 man getopt_long 
    int getopt_long_only(int argc, char * const argv[],
    const char *optstring,  //optsting是选项参数组成的字符串,如果该字符串里任一字母后有冒号,那么这个选项就要求有参数
    const struct option *longopts, int *longindex);
    返回值:每次调用该函数,它都会分析一个选项,并且返回它的短选项,
    如果分析完毕,即已经没有选项了,则会返回 - 1*/
    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;       //当处理一个带参数的选项时,全局变量optarg会指向它的参数    
            case 'p': 
         /* proxy server parsing server:port */
            tmp=strrchr(optarg,':');
            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; //getopt_long()在分析选项时,遇到一个没有定义过的选项,则返回值为‘?’
            case 'c': clients=atoi(optarg);break;
        }
    }

    /* 扫描参数选项时,optind标识下一个选项的索引;
     * 扫描结束后,标识第一个非选项参数索引;
     * 如果optind=argc,说明非选项参数即服务器URL缺失。
     * 此变量是系统定义的。
     */
    if(optind==argc) 
    {
        fprintf(stderr,"webbench: Missing URL!\n");
        usage();
        return 2;
    }

    if(clients==0) clients=1;
    if(benchtime==0) benchtime=60;
    /* Copyright */
    fprintf(stderr,"Webbench - Simple Web Benchmark "PROGRAM_VERSION"\n"
            "Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.\n");

    build_request(argv[optind]); //最后为URL,所以optind应该是URL的位置,调用生成请求信息保存在request中

    /* 以下为向屏幕打印测试相关信息*/
    printf("\nBenchmarking: ");
    switch(method)
    {
        case METHOD_GET:
        default:
            printf("GET");break;
        case METHOD_OPTIONS: 
            printf("OPTIONS");break;
        case METHOD_HEAD:
            printf("HEAD");break;
        case METHOD_TRACE:
            printf("TRACE");break;
    }
    printf(" %s",argv[optind]);
    switch(http10)
    {
        case 0: printf(" (using HTTP/0.9)");break;
        case 2: printf(" (using HTTP/1.1)");break;
    }
    printf("\n");
    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();    //返回bench()调用,核心代码,真正测试部分
}

- build_request()函数

/****************
创建URL请求连接,HTTP头
@url:url地址
创建好的请求放在全局变量request中
****************/
void build_request(const char *url)
{
    char tmp[10];
    int i;

    bzero(host,MAXHOSTNAMELEN);
    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,"://"))  //strstr(str1,str2)用于判断str2是否是str1的子串,返回开始位置
    {
        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)) //比较前7个字符串是否相同
        { 
            fprintf(stderr,"\nOnly HTTP protocol is directly supported, set --proxy for others.\n");
            exit(2);
        }
     /* protocol/host delimiter */
     i=strstr(url,"://")-url+3;   //得到地址开始的位置
     /* printf("%d\n",i); */

     if(strchr(url+i,'/')==NULL) //url+i指向http://后第一个位置
     { 
         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,'/')) //判断url中是否指定了端口号index同strstr
          {
               strncpy(host,url+i,strchr(url+i,':')-url-i); //取出主机地址
               bzero(tmp,10);
               strncpy(tmp,index(url+i,':')+1,strchr(url+i,'/')-index(url+i,':')-1);
               /* printf("tmp=%s\n",tmp); */
               proxyport=atoi(tmp); //端口号转换为int
               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()函数

/**********************
创建管道和子进程,对http请求进行测试
**********************/
/* vraci system rc error kod */
static int bench(void)
{
  int i,j,k;      //代表后续传入的speed,fail,bytes
  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();
       if(pid <= (pid_t) 0) //pid=0->子进程,pid<0->error
       {
           /* child process or error*/
           sleep(1); /* make childs faster */
           break;
           /* 子进程跳出循环orfork出错父进程跳出循环 */
       }
  }

  if( pid< (pid_t) 0) //fork出错
  {
      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);
    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);   //将数据写入管道
     fclose(f);             //写入后关闭 
     /* 子进程完成任务,返回退出 */
     return 0;
  } 
  else
  {
      /* 父进程读取管道,打印结果 */
      f=fdopen(mypipe[0],"r");
      if(f==NULL) 
      {
          perror("open pipe for reading failed.");
          return 3;
      }
      /* _IONBF(无缓冲):直接从流中读入数据或直接向流中写入数据,而没有缓冲区 */
      setvbuf(f,NULL,_IONBF,0);
      /* 虽然子进程不能污染父进程的这几个变量(因为父子进程有自己单独的一份),但用前重置一下,在这里是个好习惯 */
      speed=0;
      failed=0;
      bytes=0;
      /* 从管道中读取每个子进程的任务执行情况,并计数 */
      while(1)
      {
          pid=fscanf(f,"%d %d %d",&i,&j,&k);
          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()函数

/******************************
真正测试http的地方
@host:地址
@port:端口
@req:http格式方法
********************************/
void benchcore(const char *host,const int port,const char *req)
{
 int rlen;
 char buf[1500];
 int s,i;
 struct sigaction sa; //这个结构体的作用配合系统调用sigcation改变进程 接收到指定信号后的行动。

 /* setup alarm signal handler */
 /* 当程序执行到指定的秒数之后,发送 SIGALRM 信号 */
 sa.sa_handler=alarm_handler;
 sa.sa_flags=0;
 if(sigaction(SIGALRM,&sa,NULL))
    exit(3);
 alarm(benchtime);   
/*主要的流程是alarm()函数代表在benchtime时间后发出一个SIGALARM信号。
*而这个信号会被sigaction系统调用所捕获,当它发现有SIGALARM信号时,就会
*调用alarm_hander函数,这个函数将timerexpired 设置为1,那么下面的循环
*中判定出现1之后就会跳出,就该段循环执行了一定的时间
*/
 rlen=strlen(req);
 /* 无限执行请求,直到接收到 SIGALRM 信号将 timerexpired 设置为 1 时 */
 nexttry:while(1)
 {
    if(timerexpired)
    {
       if(failed>0)
       {
          /* fprintf(stderr,"Correcting failed by signal\n"); */
          failed--;
       }
       return;
    }
    /* 连接远程服务器 */
    s=Socket(host,port);                          
    if(s<0) { failed++;continue;}   //连接失败
    /* 发送请求 */ 
    if(rlen!=write(s,req,rlen)) {failed++;close(s);continue;}  //传送数据失败
    /* 如果是 http/0.9 则关闭 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;}    //关闭失败
    /* 成功完成一次请求,并计数,继续下一次相同的请求,直到超时为止 */
    speed++;
   }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值