1 /* 2 * (C) Radim Kolar 1997-2004 3 * This is free software, see GNU Public License version 2 for 4 * details. 5 * 6 * Simple forking WWW Server benchmark: 7 * 8 * Usage: 9 * webbench --help 10 * 11 * Return codes: 12 * 0 - sucess 13 * 1 - benchmark failed (server is not on-line) 14 * 2 - bad param 15 * 3 - internal error, fork failed 16 * 17 */ 18 #include "socket.c" 19 #include <unistd.h> 20 #include <sys/param.h> 21 #include <rpc/types.h> 22 #include <getopt.h> 23 #include <strings.h> 24 #include <time.h> 25 #include <signal.h> 26 27 /* values */ 28 volatile int timerexpired=0;//判斷測壓市場是否已經達到設定的時間 29 int speed=0;//記錄進程成功獲得服務器相應的數量 30 int failed=0;//記錄失敗的數量(speed表示成功數,failed表示失敗數) 31 int bytes=0;//記錄進程成功讀取的字節數 32 /* globals */ 33 int http10=1; /* 0 - http/0.9, 1 - http/1.0, 2 - http/1.1 *///HTTP版本 34 /* Allow: GET, HEAD, OPTIONS, TRACE */ 35 #define METHOD_GET 0 36 #define METHOD_HEAD 1 37 #define METHOD_OPTIONS 2 38 #define METHOD_TRACE 3 39 #define PROGRAM_VERSION "1.5" 40 int method=METHOD_GET;//定義HTTP請求方法:默認方式GET請求 41 int clients=1;//併發數目,默認只有一個進程發送請求,經過 -c 參數設置 42 int force=0;//是否須要等待讀取從server返回的數據,0表示要等待讀取 43 int force_reload=0;//是否使用緩存,1表示不緩存,0表示能夠緩存頁面 44 int proxyport=80;//代理服務器的端口 45 char *proxyhost=NULL;//代理服務器的端口 46 int benchtime=30;//測壓時間,默認30秒,經過 -t 參數設置 47 /* internal */ 48 int mypipe[2];//使用管道進行父進程和子進程的通訊 49 char host[MAXHOSTNAMELEN];//服務器端IP 50 #define REQUEST_SIZE 2048 51 char request[REQUEST_SIZE];//發送HTTP請求的內容 52 53 static const struct option long_options[]= 54 { 55 {"force",no_argument,&force,1}, 56 {"reload",no_argument,&force_reload,1}, 57 {"time",required_argument,NULL,'t'}, 58 {"help",no_argument,NULL,'?'}, 59 {"http09",no_argument,NULL,'9'}, 60 {"http10",no_argument,NULL,'1'}, 61 {"http11",no_argument,NULL,'2'}, 62 {"get",no_argument,&method,METHOD_GET}, 63 {"head",no_argument,&method,METHOD_HEAD}, 64 {"options",no_argument,&method,METHOD_OPTIONS}, 65 {"trace",no_argument,&method,METHOD_TRACE}, 66 {"version",no_argument,NULL,'V'}, 67 {"proxy",required_argument,NULL,'p'}, 68 {"clients",required_argument,NULL,'c'}, 69 {NULL,0,NULL,0} 70 }; 71 72 /* prototypes */ 73 static void benchcore(const char* host,const int port, const char *request); 74 static int bench(void); 75 static void build_request(const char *url); 76 77 /* 78 webbench在運行時能夠設定壓測的持續時間,以秒爲單位。 79 例如咱們但願測試30秒,也就意味着壓測30秒後程序應該退出了。 80 webbench中使用信號(signal)來控制程序結束。 81 函數1是在到達結束時間時運行的信號處理函數。 82 它僅僅是將一個記錄是否超時的變量timerexpired標記爲true。 83 後面會看到,在程序的while循環中會不斷檢測此值, 84 只有timerexpired=1,程序纔會跳出while循環並返回。 85 */ 86 static void alarm_handler(int signal) 87 { 88 timerexpired=1; 89 } 90 91 /* 92 教你如何使用webbench的函數, 93 在linux命令行調用webbench方法不對的時候運行,做爲提示。 94 有一些比較經常使用的,好比-c來指定併發進程的多少; 95 -t指定壓測的時間,以秒爲單位; 96 支持HTTP0.9,HTTP1.0,HTTP1.1三個版本; 97 支持GET,HEAD,OPTIONS,TRACE四種請求方式。 98 不要忘了調用時,命令行最後還應該附上要測的服務端URL。 99 */ 100 static void usage(void) 101 { 102 fprintf(stderr, 103 "webbench [option]... URL\n" 104 " -f|--force Don't wait for reply from server.\n" 105 " -r|--reload Send reload request - Pragma: no-cache.\n" 106 " -t|--time <sec> Run benchmark for <sec> seconds. Default 30.\n" 107 " -p|--proxy <server:port> Use proxy server for request.\n" 108 " -c|--clients <n> Run <n> HTTP clients at once. Default one.\n" 109 " -9|--http09 Use HTTP/0.9 style requests.\n" 110 " -1|--http10 Use HTTP/1.0 protocol.\n" 111 " -2|--http11 Use HTTP/1.1 protocol.\n" 112 " --get Use GET request method.\n" 113 " --head Use HEAD request method.\n" 114 " --options Use OPTIONS request method.\n" 115 " --trace Use TRACE request method.\n" 116 " -?|-h|--help This information.\n" 117 " -V|--version Display program version.\n" 118 ); 119 }; 120 int main(int argc, char *argv[]) 121 { 122 int opt=0; 123 int options_index=0; 124 char *tmp=NULL; 125 126 if(argc==1) 127 { 128 usage(); 129 return 2; 130 } 131 132 while((opt=getopt_long(argc,argv,"912Vfrt:p:c:?h",long_options,&options_index))!=EOF ) 133 { 134 switch(opt) 135 { 136 case 0 : break; 137 case 'f': force=1;break; 138 case 'r': force_reload=1;break; 139 case '9': http10=0;break; 140 case '1': http10=1;break; 141 case '2': http10=2;break; 142 case 'V': printf(PROGRAM_VERSION"\n");exit(0); 143 /** 144 *C 庫函數 int atoi(const char *str) 把參數 str 所指向的字符串轉換爲一個整數(類型爲 int 型) 145 *int atoi(const char *str) 146 *str -- 要轉換爲整數的字符串。 147 *該函數返回轉換後的長整數,若是沒有執行有效的轉換,則返回零。 148 */ 149 case 't': benchtime=atoi(optarg);break; 150 case 'p': 151 /* proxy server parsing server:port */ 152 /** 153 *strrchr() 函數用於查找某字符在字符串中最後一次出現的位置,其原型爲: 154 *char * strrchr(const char *str, int c); 155 *【參數】str 爲要查找的字符串,c 爲要查找的字符。 156 *strrchr() 將會找出 str 字符串中最後一次出現的字符 c 的地址,而後將該地址返回。 157 *注意:字符串 str 的結束標誌 NUL 也會被歸入檢索範圍,因此 str 的組後一個字符也能夠被定位。 158 *【返回值】若是找到就返回該字符最後一次出現的位置,不然返回 NULL。 159 *返回的地址是字符串在內存中隨機分配的地址再加上你所搜索的字符在字符串位置。設字符在字符串中首次出現的位置爲 i,那麼返回的地址能夠理解爲 str + i。 160 */ 161 /** 162 *optarg : char *optarg; //選項的參數指針 163 */ 164 tmp=strrchr(optarg,':'); 165 proxyhost=optarg; 166 if(tmp==NULL) 167 { 168 break; 169 } 170 if(tmp==optarg) 171 { 172 fprintf(stderr,"Error in option --proxy %s: Missing hostname.\n",optarg); 173 return 2; 174 } 175 /** 176 *C 庫函數 size_t strlen(const char *str) 計算字符串 str 的長度,直到空結束字符,但不包括空結束字符。 177 *size_t strlen(const char *str) 178 *參數:str -- 要計算長度的字符串。 179 *該函數返回字符串的長度。 180 */ 181 if(tmp==optarg+strlen(optarg)-1) 182 { 183 fprintf(stderr,"Error in option --proxy %s Port number is missing.\n",optarg); 184 return 2; 185 } 186 *tmp='\0';//把:替換爲\0 187 //從\0以後到\0以前 188 proxyport=atoi(tmp+1);break; 189 case ':': 190 case 'h': 191 case '?': usage();return 2;break; 192 case 'c': clients=atoi(optarg);break; 193 } 194 } 195 //int optind:argv的當前索引值。當getopt函數在while循環中使用時,剩下的字符串爲操做數,下標從optind到argc-1 196 //argc,argv 參考:https://www.cnblogs.com/lanshanxiao/p/11568037.html 197 //getopt_long()中的函數,參考:https://www.cnblogs.com/xhg940420/p/7016574.html 198 //掃描完畢後,optind指向非長選項和非短選項和非參數的字段,這裏應該指向URL 199 if(optind==argc) { 200 fprintf(stderr,"webbench: Missing URL!\n"); 201 usage(); 202 return 2; 203 } 204 205 if(clients==0) clients=1; 206 if(benchtime==0) benchtime=60; 207 /* Copyright */ 208 fprintf(stderr,"Webbench - Simple Web Benchmark "PROGRAM_VERSION"\n" 209 "Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.\n" 210 ); 211 /** 212 *命令讀取完成後,argv[optind]中應該存放着URL, 213 *創建完整的http請求,http請求存放在變量char request[REQUEST_SIZE]中 214 */ 215 build_request(argv[optind]); 216 /* print bench info *///輸出平臺信息 217 printf("\nBenchmarking: "); 218 switch(method) 219 { 220 case METHOD_GET: 221 default: 222 printf("GET");break; 223 case METHOD_OPTIONS: 224 printf("OPTIONS");break; 225 case METHOD_HEAD: 226 printf("HEAD");break; 227 case METHOD_TRACE: 228 printf("TRACE");break; 229 } 230 printf(" %s",argv[optind]);//打印出URL 231 switch(http10) 232 { 233 case 0: printf(" (using HTTP/0.9)");break; 234 case 2: printf(" (using HTTP/1.1)");break; 235 } 236 printf("\n"); 237 if(clients==1) printf("1 client"); 238 else 239 printf("%d clients",clients); 240 241 printf(", running %d sec", benchtime); 242 if(force) printf(", early socket close"); 243 if(proxyhost!=NULL) printf(", via proxy server %s:%d",proxyhost,proxyport); 244 if(force_reload) printf(", forcing reload"); 245 printf(".\n"); 246 //壓力測試最後一句話,全部的壓力測試都在bench函數中實現 247 return bench(); 248 } 249 250 /* 251 函數主要操做全局變量char request[REQUEST_SIZE],根據url填充其內容。 252 典型的HTTP的GET請求: 253 GET /test.jpg HTTP/1.1 254 User-Agent: WebBench 1.5 255 Host:192.168.10.1 256 Pragma: no-cache 257 Connection: close 258 259 build_request函數的目的就是要把 260 相似於以上這一大坨信息所有存到全局變量request[REQUEST_SIZE]中, 261 其中換行操做使用的是」\r\n」。 262 而以上這一大坨信息的具體內容是要根據命令行輸入的參數,以及url來肯定的。 263 該函數使用了大量的字符串操做函數, 264 例如strcpy,strstr,strncasecmp,strlen,strchr,index,strncpy,strcat。 265 對這些基礎函數不太熟悉的同窗能夠借這個函數複習一下。 266 */ 267 void build_request(const char *url) 268 { 269 char tmp[10]; 270 int i; 271 272 bzero(host,MAXHOSTNAMELEN);//bzero():置host(字節字符串)前MAXHOSTNAMELEN個字節爲0,包括'\0') 273 bzero(request,REQUEST_SIZE); 274 275 if(force_reload && proxyhost!=NULL && http10<1) http10=1;//知足必定條件,更換HTTP協議 276 if(method==METHOD_HEAD && http10<1) http10=1; 277 if(method==METHOD_OPTIONS && http10<2) http10=2; 278 if(method==METHOD_TRACE && http10<2) http10=2; 279 280 switch(method) 281 { 282 default: 283 //strcpy() 函數用於對字符串進行復制(拷貝)。 284 //char* strcpy(char* strDestination, const char* strSource); 285 //strSource 指向的字符串複製到 strDestination 286 case METHOD_GET: strcpy(request,"GET");break; 287 case METHOD_HEAD: strcpy(request,"HEAD");break; 288 case METHOD_OPTIONS: strcpy(request,"OPTIONS");break; 289 case METHOD_TRACE: strcpy(request,"TRACE");break; 290 } 291 292 //char*strcat(char* strDestination, const char* strSource); 293 /* 294 strcat() 函數用來將兩個字符串鏈接(拼接)起來。 295 strcat() 函數把 strSource 所指向的字符串追加到 strDestination 所指向的字符串的結尾, 296 因此必需要保證 strDestination 有足夠的內存空間來容納兩個字符串,不然會致使溢出錯誤。 297 注意:strDestination 末尾的\0會被覆蓋,strSource 末尾的\0會一塊兒被複制過去,最終的字符串只有一個\0。 298 */ 299 strcat(request," "); 300 301 /* 302 char *strstr(const char *haystack, const char *needle) 303 在字符串 haystack 中查找第一次出現字符串 needle 的位置,不包含終止符 '\0'。 304 該函數返回在 haystack 中第一次出現 needle 的地址,若是未找到則返回 null。 305 */ 306 if(NULL==strstr(url,"://")) 307 { 308 fprintf(stderr, "\n%s: is not a valid URL.\n",url); 309 exit(2); 310 } 311 312 /* 313 strlen(char *); 314 檢測字符串實際長度。 315 strlen(char *)檢測的是'\0',strlen(char *)碰到'\0'就返回'\0'之前的字符數(不包括'\0')。 316 strlen(char*)函數求的是字符串的實際長度,它求得方法是從開始到遇到第一個'\0', 317 若是你只定義沒有給它賦初值,這個結果是不定的,它會從aa首地址一直找下去,直到遇到'\0'中止。 318 */ 319 if(strlen(url)>1500) 320 { 321 fprintf(stderr,"URL is too long.\n"); 322 exit(2); 323 } 324 if(proxyhost==NULL) 325 /* 326 int strncasecmp(const char *s1, const char *s2, size_t n); 327 strncasecmp()用來比較參數s1 和s2 字符串前n個字符,比較時會自動忽略大小寫的差別。 328 若參數s1 和s2 字符串相同則返回0。s1 若大於s2 則返回大於0 的值,s1 若小於s2 則返回小於0 的值。 329 */ 330 if (0!=strncasecmp("http://",url,7)) 331 { 332 fprintf(stderr,"\nOnly HTTP protocol is directly supported, set --proxy for others.\n"); 333 exit(2); 334 } 335 /* protocol/host delimiter */ 336 i=strstr(url,"://")-url+3; 337 /* printf("%d\n",i); */ 338 339 /* 340 char *strchr(const char *str, char c) 341 該函數返回在字符串 str 中第一次出現字符 c 的地址,若是未找到該字符則返回 NULL。 342 */ 343 if(strchr(url+i,'/')==NULL) { 344 fprintf(stderr,"\nInvalid URL syntax - hostname don't ends with '/'.\n"); 345 exit(2); 346 } 347 if(proxyhost==NULL) 348 { 349 /* get port from hostname */ 350 if(index(url+i,':')!=NULL && 351 index(url+i,':')<index(url+i,'/')) 352 { 353 /* 354 char * strncpy(char *s1,char *s2,size_t n); 355 將字符串s2中最多n個字符複製到字符數組s1中,返回指向s1的指針。 356 注意:若是源串長度大於n,則strncpy不復制最後的'\0'結束符, 357 因此是不安全的,複製完後須要手動添加字符串的結束符才行。 358 */ 359 strncpy(host,url+i,strchr(url+i,':')-url-i); 360 bzero(tmp,10); 361 strncpy(tmp,index(url+i,':')+1,strchr(url+i,'/')-index(url+i,':')-1); 362 /* printf("tmp=%s\n",tmp); */ 363 364 /* 365 C語言庫函數名: atoi 366 功 能: 把字符串轉換成整型數. 367 名字來源:array to integer 的縮寫. 368 函數說明: atoi()會掃描參數nptr字符串,若是第一個字符不是數字也不是正負號返回零, 369 不然開始作類型轉換,以後檢測到非數字或結束符 \0 時中止轉換,返回整型數。 370 原型: int atoi(const char *nptr); 371 */ 372 proxyport=atoi(tmp); 373 if(proxyport==0) proxyport=80; 374 } else 375 { 376 /* 377 size_t strcspn(const char *s, const char * reject); 378 函數說明:strcspn()從參數s 字符串的開頭計算連續的字符, 379 而這些字符都徹底不在參數reject 所指的字符串中。 380 簡單地說, 若strcspn()返回的數值爲n,則表明字符串s 開頭連續有n 個字符都不含字符串reject 內的字符。 381 返回值:返回字符串s 開頭連續不含字符串reject 內的字符數目。 382 */ 383 strncpy(host,url+i,strcspn(url+i,"/")); 384 } 385 // printf("Host=%s\n",host); 386 strcat(request+strlen(request),url+i+strcspn(url+i,"/")); 387 } else 388 { 389 // printf("ProxyHost=%s\nProxyPort=%d\n",proxyhost,proxyport); 390 strcat(request,url); 391 } 392 if(http10==1) 393 strcat(request," HTTP/1.0"); 394 else if (http10==2) 395 strcat(request," HTTP/1.1"); 396 strcat(request,"\r\n"); 397 if(http10>0) 398 strcat(request,"User-Agent: WebBench "PROGRAM_VERSION"\r\n"); 399 if(proxyhost==NULL && http10>0) 400 { 401 strcat(request,"Host: "); 402 strcat(request,host); 403 strcat(request,"\r\n"); 404 } 405 if(force_reload && proxyhost!=NULL) 406 { 407 strcat(request,"Pragma: no-cache\r\n"); 408 } 409 if(http10>1) 410 strcat(request,"Connection: close\r\n"); 411 /* add empty line at end */ 412 if(http10>0) strcat(request,"\r\n"); 413 // printf("Req=%s\n",request); 414 } 415 416 /** 417 *先進行了一次socket鏈接,確認能連通之後,才進行後續步驟。 418 *調用pipe函數初始化一個管道,用於子進行向父進程彙報測試數據。 419 *子進程根據clients數量fork出來。 420 *每一個子進程都調用函數5進行測試,並將結果輸出到管道,供父進程讀取。 421 *父進程負責收集全部子進程的測試數據,並彙總輸出。 422 */ 423 /* vraci system rc error kod */ 424 static int bench(void) 425 { 426 int i,j,k; 427 pid_t pid=0; 428 FILE *f; 429 430 /* check avaibility of target server */ 431 //檢測目標服務器的可用性,調用socket.c文件中的函數 432 i=Socket(proxyhost==NULL?host:proxyhost,proxyport); 433 if(i<0) {//處理錯誤 434 fprintf(stderr,"\nConnect to server failed. Aborting benchmark.\n"); 435 return 1; 436 } 437 close(i); 438 /* create pipe */ 439 if(pipe(mypipe))//管道用於子進程向父進程回報數據 440 {//錯誤處理 441 perror("pipe failed."); 442 return 3; 443 } 444 445 /* not needed, since we have alarm() in childrens */ 446 /* wait 4 next system clock tick */ 447 /* 448 cas=time(NULL); 449 while(time(NULL)==cas) 450 sched_yield(); 451 */ 452 453 /* fork childs */ 454 for(i=0;i<clients;i++)//根據clients大小fork出來足夠的子進程進行測試 455 { 456 pid=fork(); 457 if(pid <= (pid_t) 0) 458 { 459 /* child process or error*/ 460 sleep(1); /* make childs faster */ 461 break; 462 } 463 } 464 465 if( pid< (pid_t) 0) 466 {//錯誤處理 467 fprintf(stderr,"problems forking worker no. %d\n",i); 468 perror("fork failed."); 469 return 3; 470 } 471 472 if(pid== (pid_t) 0)//如果子進程,調用benchcore進行測試 473 { 474 /* I am a child */ 475 if(proxyhost==NULL) 476 benchcore(host,proxyport,request); 477 else 478 benchcore(proxyhost,proxyport,request); 479 480 /* write results to pipe */ 481 f=fdopen(mypipe[1],"w");//子進程將測試結果輸出到管道 482 if(f==NULL) 483 {//錯誤處理 484 perror("open pipe for writing failed."); 485 return 3; 486 } 487 /* fprintf(stderr,"Child - %d %d\n",speed,failed); */ 488 fprintf(f,"%d %d %d\n",speed,failed,bytes); 489 fclose(f); 490 return 0; 491 } else 492 {//如果父進程,則從管道讀取子進程輸出,並作彙總 493 f=fdopen(mypipe[0],"r"); 494 if(f==NULL) 495 {//錯誤處理 496 perror("open pipe for reading failed."); 497 return 3; 498 } 499 setvbuf(f,NULL,_IONBF,0); 500 speed=0; 501 failed=0; 502 bytes=0; 503 504 while(1) 505 {//從管道讀取數據,fscanf爲阻塞式函數 506 pid=fscanf(f,"%d %d %d",&i,&j,&k); 507 if(pid<2) 508 {//錯誤處理 509 fprintf(stderr,"Some of our childrens died.\n"); 510 break; 511 } 512 speed+=i; 513 failed+=j; 514 bytes+=k; 515 /* fprintf(stderr,"*Knock* %d %d read=%d\n",speed,failed,pid); */ 516 if(--clients==0) break;//這句用於記錄已經讀了多少個子進程的數據,讀完就退出 517 } 518 fclose(f); 519 //最後將結果打印到屏幕上 520 printf("\nSpeed=%d pages/min, %d bytes/sec.\nRequests: %d susceed, %d failed.\n", 521 (int)((speed+failed)/(benchtime/60.0f)), 522 (int)(bytes/(float)benchtime), 523 speed, 524 failed); 525 } 526 return i; 527 } 528 529 /** 530 *benchcore是子進程進行壓力測試的函數,被每一個子進程調用。 531 *這裏使用了SIGALRM信號來控制時間, 532 *alarm函數設置了多少時間以後產生SIGALRM信號,一旦產生此信號,將運行alarm_handler(), 533 *使得timerexpired=1,這樣能夠經過判斷timerexpired值來退出程序。 534 *另外,全局變量force表示咱們是否在發出請求後須要等待服務器的響應結果 535 */ 536 void benchcore(const char *host,const int port,const char *req) 537 { 538 int rlen; 539 char buf[1500];//記錄服務器響應請求所返回的數據 540 int s,i; 541 struct sigaction sa; 542 543 /* setup alarm signal handler */ 544 sa.sa_handler=alarm_handler;//將函數alarm_handler地址賦值給sa.alarm_handler,做爲信號處理函數 545 sa.sa_flags=0; 546 if(sigaction(SIGALRM,&sa,NULL))//超時會產生信號SIGALRM,用sa中的指定函數處理 547 exit(3); 548 alarm(benchtime);//開始計時 549 550 rlen=strlen(req); 551 nexttry:while(1) 552 { 553 if(timerexpired)//一旦超時則返回 554 { 555 if(failed>0) 556 { 557 /* fprintf(stderr,"Correcting failed by signal\n"); */ 558 failed--; 559 } 560 return; 561 } 562 s=Socket(host,port);//調用socket創建TCP鏈接 563 if(s<0) { failed++;continue;} 564 if(rlen!=write(s,req,rlen)) {failed++;close(s);continue;}//發出請求 565 if(http10==0) //針對http0.9作的特殊處理 566 if(shutdown(s,1)) { failed++;close(s);continue;} 567 if(force==0) //全局變量force表示是否要等待服務器返回的數據 568 { 569 /* read all available data from socket */ 570 while(1) 571 { 572 if(timerexpired) break; 573 i=read(s,buf,1500);//從socket讀取返回數據 574 /* fprintf(stderr,"%d\n",i); */ 575 if(i<0) 576 { 577 failed++; 578 close(s); 579 goto nexttry; 580 } 581 else 582 if(i==0) break; 583 else 584 bytes+=i; 585 } 586 } 587 if(close(s)) {failed++;continue;} 588 speed++; 589 } 590 }