Webbench Source Code Analysis

Source: Internet
Author: User

Webbench is a Web site pressure measurement tool that is used under Linux. It uses fork () to simulate multiple clients accessing the URL we set at the same time, testing the performance of the site under pressure, and simulating up to 30,000 concurrent connections to test the load capacity of the site. The source code adds up to less than 600 lines.

Download link

Although the code is not much, but the function is very practical, by reading this code for learning Linux under the socket, fork mechanism and command line parameter parsing is very helpful. Here is the note that I read about the code record.

Source files on two, one is socket.c, processing socket connection. Very simple, the code is as follows:

/*getopt_long is used to handle command-line arguments, the first two arguments are the argc,argv that the main function passes over. The third parameter, optstring, is a string that represents the parameters that can be accepted. For example, "A:B:CD", which means that an acceptable parameter is a,b,c,d, where the A and B parameters are preceded by a colon, indicating that more parameter values are followed. (For example:-a host-b name) such as this code, indicating that the Webbench command can support commands such as -9,-F-T, where-P, the-c parameter must be followed by a parameter value, such as-P 9000. */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);   Optarg represents a parameter after the command, such as-C 100,optarg is 100. Case ' P ':/* Proxy Server parsing Server:port */* Find a character C in another string str in the last occurrence of the position (that is, starting from the right of STR to find the first occurrence of the character C Position) and returns all characters from this position in the string until the end of the string.         If the specified character cannot be found, then the function returns NULL. If an option takes parameters, such as-P 192.168.0.1:9800, Optarg points to its arguments, which is "192.168.0.1:9800" then ProxyHost is 192.168.0.1 and ProxyPort is 98. XX */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) {printf ("tmp:%s\n", TMP);             fprintf (stderr, "Error in option--proxy%s Port number is missing.\n", optarg);         return 2;         } *tmp= ' + ';   Proxyport=atoi (tmp+1);   Case ': ': Case ' h ': Case '? ': usage (); return 2;break;  Case ' C ': Clients=atoi (Optarg); }}/* This sentence is a bit difficult to understand, in fact, it is this: Getopt_long first argv The parameters of the non-option to the argv backend, which allows option to become position-independent, optind the initial value of 1,getopt will gradually traverse argv, Each call will have Optind point to the next option indexed in argv, and each time Optind moves depends on optstring:1. Encountered "X", option without parameters, Optind + = 1 2. Encountered "x:", option with parameters, Optarg = Argv[optind + 1], optind + = 2 If all goes well, the last optind should point to the first non-option parameter, if Optind >= argc, the description does not already have no parameters if with u RL, like this, webbench-c http://www.baidu.com/so, optind=3, ARGc=4, and then optind points to the index of the 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-2 004, GPL Open Source software.\n "); Build_request (Argv[optind]); Build_request used to organize HTTP requests,//create HTTP connection request void Build_request (const char *url) {char tmp[10] = {  0};  int i;  printf ("url:%s\n", url);  Bzero (Host,maxhostnamelen);  Bzero (request,request_size); Refers to the minimum use of the HTTP1.0 protocol when caching and proxies are used.  Version 0.9, no proxy concept, no caching concept??  A force_reload of 1 means that there is no cache 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;  printf ("method:%d\n", method);   Switch (method) {   Default:case method_get:strcpy (Request, "GET");      Case method_head:strcpy (Request, "HEAD");      Case method_options:strcpy (Request, "OPTIONS");  Case method_trace:strcpy (Request, "TRACE");  } strcat (Request, "");    printf ("request:%s\n", request); The STRSTR (STR1,STR2) function is used to determine if the string str2 is a substring of str1 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 the parameter does not indicate a port, then 80, 80 port is open for HTTP (Hypertext Transport Protocol) is the Hypertext Transfer Protocol, this is the most frequently used Internet surfing protocol, mainly used in www (World Wide Web) is the World Wide Web protocol for transmitting information.  The website can be accessed via HTTP address (ie, "url") and ": 80" because the default port number is 80, so just enter the URL and do not enter ": 80".       Of course, you can also specify the port, such as: webbench-c http://www.baidu.com:9800/*/if (proxyhost==null) {/* get port from hostname */ if (Index (Url+i, ': ')!=null && index (url+i, ': ') <index (url+i, '/')) {strncpy (host,u RL+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);       if (proxyport==0) proxyport=80; } else {//STRCSPN Returns the subscript value of the first occurrence of the character in S1, that is, the length of the substring that appears in S1 and does not appear in S2 strncpy (host,url+i,strcspn (Url+i, "/"))       ;           } printf ("host=%s\n", Host);        strcat (Request+strlen (Request), url+i+strcspn (Url+i, "/"));  printf ("request=%s\n", request);   } else {printf ("proxyhost=%s\nproxyport=%d\n", Proxyhost,proxyport);   strcat (Request,url);  printf ("request=%s\n", request); }

The Build_request function also involves a problem, that is, the protocol of the HTTP request, which does not speak much of it, but only its basic format:
* Request Line
* Headers
* Blank Line
* Request-body

Next is the bench function, which creates a constant "attack" target address for multiple sub-processes by fork.

/* VRACI system RC error kod */static int bench (void) {int i,j,k;  pid_t pid=0;  FILE *f;  printf ("bench.....\n");  /* 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 */* define function: int pipe (int filedes[2]);               3) function Description: Pipe () creates a pipeline and returns the file descriptor as a parameter filedes array.      Filedes[0] is the read end of the pipeline filedes[1] is the write end of the pipeline */if (pipe (mypipe)) {perror ("pipe failed.");  return 3;  }/* Not needed, since we had 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) {/* child process or error*/////The purpose of this code is to generate a subprocess, when the fork has 2 processes executed.     When the fork is wrong or the fork executes to the child process, sleep (1), let out the CPU, allow the parent process to take the CPU to continue the for loop, fork to generate the child process.          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 *///Sub-process writes data to the pipeline, sending the result if (proxyhost==null) Benchcore (host,proxyport,r         Equest);         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 {/* I am the father *///parent process reads data from the pipe, showing the result 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);                       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;} void Benchcore (const char *host,const int Port,const char *req) {int rlen; char buf[1500] = {0}; int s,i;/*sigaction function is used to change The behavior of the variable process after it receives a specific signal. The first parameter of the function is the value of the signal, sigalrm a signal emitted by alarm (2) The second parameter is a pointer to an instance of the structure sigaction, in the case of structure sigaction, specifies the processing of a particular signal, The third parameter, Oldact, points to the object used to hold the returned original processing of the corresponding signal, optionally specifying oldact as NULL. The system calls alarm to schedule the kernel to emit a SIGALRM signal for the calling process after the specified seconds seconds. If the specified parameter seconds is 0, the SIGALRM signal is no longer sent. The next setting cancels the previous setting. The call returns a value of the last timedUse the time remaining between sends, or return 0 because there is no previous scheduled call. Note that when used, the alarm is only set to send a signal once, and if it is to be sent multiple times, it will be called multiple times using alarm. */struct sigaction sa; /* Setup Alarm Signal handler */Sa.sa_handler=alarm_handler; sa.sa_flags=0; if (Sigaction (Sigalrm,&sa,null)) exit (3); This is equivalent to setting a benchtime time alarm clock, limit the socket access time alarm (benchtime); Rlen=strlen (req);  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;}    Send HTTP request message if (Rlen!=write (S,req,rlen)) {failed++;close (s); continue;}    if (http10==0) if (Shutdown (s,1)) {failed++;close (s); continue;} if (force==0) {/* read all available data from Socket */while (1) {if (Timerexpir          ed) 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++; }}

Webbench Source Analysis

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.