Back to index

lightning-sunbird  0.9+nobinonly
servr_uk.c
Go to the documentation of this file.
00001 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
00002 /* ***** BEGIN LICENSE BLOCK *****
00003  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
00004  *
00005  * The contents of this file are subject to the Mozilla Public License Version
00006  * 1.1 (the "License"); you may not use this file except in compliance with
00007  * the License. You may obtain a copy of the License at
00008  * http://www.mozilla.org/MPL/
00009  *
00010  * Software distributed under the License is distributed on an "AS IS" basis,
00011  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
00012  * for the specific language governing rights and limitations under the
00013  * License.
00014  *
00015  * The Original Code is the Netscape Portable Runtime (NSPR).
00016  *
00017  * The Initial Developer of the Original Code is
00018  * Netscape Communications Corporation.
00019  * Portions created by the Initial Developer are Copyright (C) 1998-2000
00020  * the Initial Developer. All Rights Reserved.
00021  *
00022  * Contributor(s):
00023  *
00024  * Alternatively, the contents of this file may be used under the terms of
00025  * either the GNU General Public License Version 2 or later (the "GPL"), or
00026  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
00027  * in which case the provisions of the GPL or the LGPL are applicable instead
00028  * of those above. If you wish to allow use of your version of this file only
00029  * under the terms of either the GPL or the LGPL, and not to allow others to
00030  * use your version of this file under the terms of the MPL, indicate your
00031  * decision by deleting the provisions above and replace them with the notice
00032  * and other provisions required by the GPL or the LGPL. If you do not delete
00033  * the provisions above, a recipient may use your version of this file under
00034  * the terms of any one of the MPL, the GPL or the LGPL.
00035  *
00036  * ***** END LICENSE BLOCK ***** */
00037 
00038 /***********************************************************************
00039 **
00040 ** This server simulates a server running in loopback mode.
00041 **
00042 ** The idea is that a single server is created.  The server initially creates
00043 ** a number of worker threads.  Then, with the server running, a number of 
00044 ** clients are created which start requesting service from the server.
00045 **
00046 **
00047 ** Modification History:
00048 ** 19-May-97 AGarcia- Converted the test to accomodate the debug_mode flag.
00049 **              The debug mode will print all of the printfs associated with this test.
00050 **                    The regress mode will be the default mode. Since the regress tool limits
00051 **           the output to a one line status:PASS or FAIL,all of the printf statements
00052 **                    have been handled with an if (debug_mode) statement.
00053 ** 04-June-97 AGarcia removed the Test_Result function. Regress tool has been updated to
00054 **                   recognize the return code from tha main program.
00055 ***********************************************************************/
00056 
00057 /***********************************************************************
00058 ** Includes
00059 ***********************************************************************/
00060 /* Used to get the command line option */
00061 #include "plgetopt.h"
00062 
00063 #include "nspr.h"
00064 #include "pprthred.h"
00065 
00066 #include <string.h>
00067 
00068 #define PORT 15004
00069 #define THREAD_STACKSIZE 0
00070 
00071 static int _iterations = 1000;
00072 static int _clients = 1;
00073 static int _client_data = 250;
00074 static int _server_data = (8*1024);
00075 
00076 static PRThreadScope ServerScope, ClientScope;
00077 
00078 #define SERVER "Server"
00079 #define MAIN   "Main"
00080 
00081 #define SERVER_STATE_STARTUP 0
00082 #define SERVER_STATE_READY   1
00083 #define SERVER_STATE_DYING   2
00084 #define SERVER_STATE_DEAD    4
00085 int       ServerState;
00086 PRLock    *ServerStateCVLock;
00087 PRCondVar *ServerStateCV;
00088 
00089 #ifdef DEBUGPRINTS
00090 #define DPRINTF printf
00091 #else
00092 #define DPRINTF
00093 #endif
00094 
00095 PRIntn failed_already=0;
00096 PRIntn debug_mode;
00097 
00098 
00099 
00100 static void do_work(void);
00101 
00102 /* --- Server state functions --------------------------------------------- */
00103 void
00104 SetServerState(char *waiter, PRInt32 state)
00105 {
00106     PR_Lock(ServerStateCVLock);
00107     ServerState = state;
00108     PR_NotifyCondVar(ServerStateCV);
00109 
00110        if (debug_mode) DPRINTF("\t%s changed state to %d\n", waiter, state);
00111 
00112     PR_Unlock(ServerStateCVLock);
00113 }
00114 
00115 int
00116 WaitServerState(char *waiter, PRInt32 state)
00117 {
00118     PRInt32 rv;
00119 
00120     PR_Lock(ServerStateCVLock);
00121 
00122     if (debug_mode) DPRINTF("\t%s waiting for state %d\n", waiter, state);
00123 
00124     while(!(ServerState & state))
00125         PR_WaitCondVar(ServerStateCV, PR_INTERVAL_NO_TIMEOUT);
00126     rv = ServerState;
00127 
00128     if (debug_mode) DPRINTF("\t%s resuming from wait for state %d; state now %d\n", 
00129         waiter, state, ServerState);
00130     PR_Unlock(ServerStateCVLock);
00131 
00132     return rv;
00133 }
00134 
00135 /* --- Server Functions ------------------------------------------- */
00136 
00137 PRLock *workerThreadsLock;
00138 PRInt32 workerThreads;
00139 PRInt32 workerThreadsBusy;
00140 
00141 void
00142 WorkerThreadFunc(void *_listenSock)
00143 {
00144     PRFileDesc *listenSock = (PRFileDesc *)_listenSock;
00145     PRInt32 bytesRead;
00146     PRInt32 bytesWritten;
00147     char *dataBuf;
00148     char *sendBuf;
00149 
00150     if (debug_mode) DPRINTF("\tServer buffer is %d bytes; %d data, %d netaddrs\n",
00151             _client_data+(2*sizeof(PRNetAddr))+32, _client_data, (2*sizeof(PRNetAddr))+32);
00152     dataBuf = (char *)PR_MALLOC(_client_data + 2*sizeof(PRNetAddr) + 32);
00153     if (!dataBuf)
00154         if (debug_mode) printf("\tServer could not malloc space!?\n");
00155     sendBuf = (char *)PR_MALLOC(_server_data *sizeof(char));
00156     if (!sendBuf)
00157         if (debug_mode) printf("\tServer could not malloc space!?\n");
00158 
00159     if (debug_mode) DPRINTF("\tServer worker thread running\n");
00160 
00161     while(1) {
00162         PRInt32 bytesToRead = _client_data;
00163         PRInt32 bytesToWrite = _server_data;
00164         PRFileDesc *newSock;
00165         PRNetAddr *rAddr;
00166         PRInt32 loops = 0;
00167 
00168         loops++;
00169 
00170         if (debug_mode) DPRINTF("\tServer thread going into accept\n");
00171 
00172         bytesRead = PR_AcceptRead(listenSock, 
00173                                   &newSock,
00174                                   &rAddr,
00175                                   dataBuf,
00176                                   bytesToRead,
00177                                   PR_INTERVAL_NO_TIMEOUT);
00178 
00179         if (bytesRead < 0) {
00180             if (debug_mode) printf("\tServer error in accept (%d)\n", bytesRead);
00181             continue;
00182         }
00183 
00184         if (debug_mode) DPRINTF("\tServer accepted connection (%d bytes)\n", bytesRead);
00185         
00186         PR_AtomicIncrement(&workerThreadsBusy);
00187         if (workerThreadsBusy == workerThreads) {
00188 
00189             PR_Lock(workerThreadsLock);
00190             if (workerThreadsBusy == workerThreads) {
00191                 PRThread *WorkerThread;
00192 
00193                 WorkerThread = PR_CreateThread(
00194                                   PR_SYSTEM_THREAD,
00195                                   WorkerThreadFunc,
00196                                   listenSock,
00197                                   PR_PRIORITY_NORMAL,
00198                                   ServerScope,
00199                                   PR_UNJOINABLE_THREAD,
00200                                   THREAD_STACKSIZE);
00201 
00202                 if (!WorkerThread) {
00203                     if (debug_mode) printf("Error creating client thread %d\n", workerThreads);
00204                 } else {
00205                     PR_AtomicIncrement(&workerThreads);
00206                     if (debug_mode) DPRINTF("\tServer creates worker (%d)\n", workerThreads);
00207                 }
00208             }
00209             PR_Unlock(workerThreadsLock);
00210         }
00211  
00212         bytesToRead -= bytesRead;
00213         while (bytesToRead) {
00214             bytesRead = PR_Recv(newSock, 
00215                                 dataBuf, 
00216                                 bytesToRead, 
00217                                 0, 
00218                                 PR_INTERVAL_NO_TIMEOUT);
00219             if (bytesRead < 0) {
00220                 if (debug_mode) printf("\tServer error receiving data (%d)\n", bytesRead);
00221                 continue;
00222             }
00223             if (debug_mode) DPRINTF("\tServer received %d bytes\n", bytesRead);
00224         }
00225 
00226         bytesWritten = PR_Send(newSock,
00227                                sendBuf, 
00228                                bytesToWrite, 
00229                                0, 
00230                                PR_INTERVAL_NO_TIMEOUT);
00231         if (bytesWritten != _server_data) {
00232             if (debug_mode) printf("\tError sending data to client (%d, %d)\n", 
00233                 bytesWritten, PR_GetOSError());
00234         } else {
00235             if (debug_mode) DPRINTF("\tServer sent %d bytes\n", bytesWritten);
00236         }
00237 
00238         PR_Close(newSock);
00239         PR_AtomicDecrement(&workerThreadsBusy);
00240     }
00241 }
00242 
00243 PRFileDesc *
00244 ServerSetup(void)
00245 {
00246     PRFileDesc *listenSocket;
00247     PRSocketOptionData sockOpt;
00248     PRNetAddr serverAddr;
00249     PRThread *WorkerThread;
00250 
00251     if ( (listenSocket = PR_NewTCPSocket()) == NULL) {
00252         if (debug_mode) printf("\tServer error creating listen socket\n");
00253               else 
00254         return NULL;
00255     }
00256 
00257     sockOpt.option = PR_SockOpt_Reuseaddr;
00258     sockOpt.value.reuse_addr = PR_TRUE;
00259     if ( PR_SetSocketOption(listenSocket, &sockOpt) == PR_FAILURE) {
00260         if (debug_mode) printf("\tServer error setting socket option: OS error %d\n",
00261                 PR_GetOSError());
00262               else failed_already=1;
00263         PR_Close(listenSocket);
00264         return NULL;
00265     }
00266 
00267     memset(&serverAddr, 0, sizeof(PRNetAddr));
00268     serverAddr.inet.family = PR_AF_INET;
00269     serverAddr.inet.port = PR_htons(PORT);
00270     serverAddr.inet.ip = PR_htonl(PR_INADDR_ANY);
00271 
00272     if ( PR_Bind(listenSocket, &serverAddr) == PR_FAILURE) {
00273         if (debug_mode) printf("\tServer error binding to server address: OS error %d\n",
00274                 PR_GetOSError());
00275               else failed_already=1;
00276         PR_Close(listenSocket);
00277         return NULL;
00278     }
00279 
00280     if ( PR_Listen(listenSocket, 128) == PR_FAILURE) {
00281         if (debug_mode) printf("\tServer error listening to server socket\n");
00282               else failed_already=1;
00283         PR_Close(listenSocket);
00284 
00285         return NULL;
00286     }
00287 
00288     /* Create Clients */
00289     workerThreads = 0;
00290     workerThreadsBusy = 0;
00291 
00292     workerThreadsLock = PR_NewLock();
00293 
00294     WorkerThread = PR_CreateThread(
00295                       PR_SYSTEM_THREAD,
00296                       WorkerThreadFunc,
00297                       listenSocket,
00298                       PR_PRIORITY_NORMAL,
00299                       ServerScope,
00300                       PR_UNJOINABLE_THREAD,
00301                       THREAD_STACKSIZE);
00302 
00303     if (!WorkerThread) {
00304         if (debug_mode) printf("error creating working thread\n");
00305         PR_Close(listenSocket);
00306         return NULL;
00307     }
00308     PR_AtomicIncrement(&workerThreads);
00309     if (debug_mode) DPRINTF("\tServer created primordial worker thread\n");
00310 
00311     return listenSocket;
00312 }
00313 
00314 /* The main server loop */
00315 void
00316 ServerThreadFunc(void *unused)
00317 {
00318     PRFileDesc *listenSocket;
00319 
00320     /* Do setup */
00321     listenSocket = ServerSetup();
00322 
00323     if (!listenSocket) {
00324         SetServerState(SERVER, SERVER_STATE_DEAD);
00325     } else {
00326 
00327         if (debug_mode) DPRINTF("\tServer up\n");
00328 
00329         /* Tell clients they can start now. */
00330         SetServerState(SERVER, SERVER_STATE_READY);
00331 
00332         /* Now wait for server death signal */
00333         WaitServerState(SERVER, SERVER_STATE_DYING);
00334 
00335         /* Cleanup */
00336         SetServerState(SERVER, SERVER_STATE_DEAD);
00337     }
00338 }
00339 
00340 /* --- Client Functions ------------------------------------------- */
00341 
00342 PRInt32 numRequests;
00343 PRInt32 numClients;
00344 PRMonitor *clientMonitor;
00345 
00346 void
00347 ClientThreadFunc(void *unused)
00348 {
00349     PRNetAddr serverAddr;
00350     PRFileDesc *clientSocket;
00351     char *sendBuf;
00352     char *recvBuf;
00353     PRInt32 rv;
00354     PRInt32 bytesNeeded;
00355 
00356     sendBuf = (char *)PR_MALLOC(_client_data * sizeof(char));
00357     if (!sendBuf)
00358         if (debug_mode) printf("\tClient could not malloc space!?\n");
00359     recvBuf = (char *)PR_MALLOC(_server_data * sizeof(char));
00360     if (!recvBuf)
00361         if (debug_mode) printf("\tClient could not malloc space!?\n");
00362 
00363     memset(&serverAddr, 0, sizeof(PRNetAddr));
00364     serverAddr.inet.family = PR_AF_INET;
00365     serverAddr.inet.port = PR_htons(PORT);
00366     serverAddr.inet.ip = PR_htonl(PR_INADDR_LOOPBACK);
00367 
00368     while(numRequests > 0) {
00369 
00370         if ( (numRequests % 10) == 0 )
00371             if (debug_mode) printf(".");
00372         if (debug_mode) DPRINTF("\tClient starting request %d\n", numRequests);
00373 
00374         clientSocket = PR_NewTCPSocket();
00375         if (!clientSocket) {
00376             if (debug_mode) printf("Client error creating socket: OS error %d\n",
00377                   PR_GetOSError());
00378             continue;
00379         }
00380 
00381         if (debug_mode) DPRINTF("\tClient connecting\n");
00382 
00383         rv = PR_Connect(clientSocket, 
00384                         &serverAddr,
00385                         PR_INTERVAL_NO_TIMEOUT);
00386         if (!clientSocket) {
00387             if (debug_mode) printf("\tClient error connecting\n");
00388             continue;
00389         }
00390 
00391         if (debug_mode) DPRINTF("\tClient connected\n");
00392 
00393         rv = PR_Send(clientSocket, 
00394                      sendBuf, 
00395                      _client_data, 
00396                      0, 
00397                      PR_INTERVAL_NO_TIMEOUT);
00398         if (rv != _client_data) {
00399             if (debug_mode) printf("Client error sending data (%d)\n", rv);
00400             PR_Close(clientSocket);
00401             continue;
00402         }
00403 
00404         if (debug_mode) DPRINTF("\tClient sent %d bytes\n", rv);
00405 
00406         bytesNeeded = _server_data;
00407         while(bytesNeeded) {
00408             rv = PR_Recv(clientSocket, 
00409                          recvBuf, 
00410                          bytesNeeded, 
00411                          0, 
00412                          PR_INTERVAL_NO_TIMEOUT);
00413             if (rv <= 0) {
00414                 if (debug_mode) printf("Client error receiving data (%d) (%d/%d)\n", 
00415                     rv, (_server_data - bytesNeeded), _server_data);
00416                 break;
00417             }
00418             if (debug_mode) DPRINTF("\tClient received %d bytes; need %d more\n", rv, bytesNeeded - rv);
00419             bytesNeeded -= rv;
00420         }
00421 
00422         PR_Close(clientSocket);
00423  
00424         PR_AtomicDecrement(&numRequests);
00425     }
00426 
00427     PR_EnterMonitor(clientMonitor);
00428     --numClients;
00429     PR_Notify(clientMonitor);
00430     PR_ExitMonitor(clientMonitor);
00431 
00432     PR_DELETE(sendBuf);
00433     PR_DELETE(recvBuf);
00434 }
00435 
00436 void
00437 RunClients(void)
00438 {
00439     PRInt32 index;
00440 
00441     numRequests = _iterations;
00442     numClients = _clients;
00443     clientMonitor = PR_NewMonitor();
00444 
00445     for (index=0; index<_clients; index++) {
00446         PRThread *clientThread;
00447 
00448   
00449         clientThread = PR_CreateThread(
00450                           PR_USER_THREAD,
00451                           ClientThreadFunc,
00452                           NULL,
00453                           PR_PRIORITY_NORMAL,
00454                           ClientScope,
00455                           PR_UNJOINABLE_THREAD,
00456                           THREAD_STACKSIZE);
00457 
00458         if (!clientThread) {
00459             if (debug_mode) printf("\terror creating client thread %d\n", index);
00460         } else
00461             if (debug_mode) DPRINTF("\tMain created client %d/%d\n", index+1, _clients);
00462 
00463     }
00464 
00465     PR_EnterMonitor(clientMonitor);
00466     while(numClients)
00467         PR_Wait(clientMonitor, PR_INTERVAL_NO_TIMEOUT);
00468     PR_ExitMonitor(clientMonitor);
00469 }
00470 
00471 /* --- Main Function ---------------------------------------------- */
00472 
00473 static
00474 void do_work()
00475 {
00476     PRThread *ServerThread;
00477     PRInt32 state;
00478 
00479     SetServerState(MAIN, SERVER_STATE_STARTUP);
00480     ServerThread = PR_CreateThread(
00481                       PR_USER_THREAD,
00482                       ServerThreadFunc,
00483                       NULL,
00484                       PR_PRIORITY_NORMAL,
00485                       ServerScope,
00486                       PR_JOINABLE_THREAD,
00487                       THREAD_STACKSIZE);
00488     if (!ServerThread) {
00489         if (debug_mode) printf("error creating main server thread\n");
00490         return;
00491     }
00492 
00493     /* Wait for server to be ready */
00494     state = WaitServerState(MAIN, SERVER_STATE_READY|SERVER_STATE_DEAD);
00495 
00496     if (!(state & SERVER_STATE_DEAD)) {
00497         /* Run Test Clients */
00498         RunClients();
00499 
00500         /* Send death signal to server */
00501         SetServerState(MAIN, SERVER_STATE_DYING);
00502     }
00503 
00504     PR_JoinThread(ServerThread);
00505 }
00506 
00507 
00508 static void do_workUK(void)
00509 {
00510     ServerScope = PR_LOCAL_THREAD;
00511     ClientScope = PR_GLOBAL_THREAD;
00512     do_work();
00513 }
00514 
00515 
00516 
00517 static void Measure(void (*func)(void), const char *msg)
00518 {
00519     PRIntervalTime start, stop;
00520     double d;
00521 
00522     start = PR_IntervalNow();
00523     (*func)();
00524     stop = PR_IntervalNow();
00525 
00526     d = (double)PR_IntervalToMicroseconds(stop - start);
00527 
00528     if (debug_mode) printf("\n%40s: %6.2f usec\n", msg, d / _iterations);
00529 }
00530 
00531 
00532 main(int argc, char **argv)
00533 {
00534        /* The command line argument: -d is used to determine if the test is being run
00535        in debug mode. The regress tool requires only one line output:PASS or FAIL.
00536        All of the printfs associated with this test has been handled with a if (debug_mode)
00537        test.
00538        Usage: test_name -d
00539        */
00540        PLOptStatus os;
00541        PLOptState *opt = PL_CreateOptState(argc, argv, "d:");
00542        while (PL_OPT_EOL != (os = PL_GetNextOpt(opt)))
00543     {
00544               if (PL_OPT_BAD == os) continue;
00545         switch (opt->option)
00546         {
00547         case 'd':  /* debug mode */
00548                      debug_mode = 1;
00549             break;
00550          default:
00551             break;
00552         }
00553     }
00554        PL_DestroyOptState(opt);
00555 
00556  /* main test */
00557     if (debug_mode) {
00558               printf("Enter number of iterations: \n");
00559               scanf("%d", &_iterations);
00560               printf("Enter number of clients   : \n");
00561               scanf("%d", &_clients);
00562               printf("Enter size of client data : \n");
00563               scanf("%d", &_client_data);
00564               printf("Enter size of server data : \n");
00565               scanf("%d", &_server_data);
00566        }
00567        else {
00568               _iterations = 7;
00569               _clients = 7;
00570               _client_data = 100;
00571               _server_data = 100;
00572        }
00573 
00574     if (debug_mode) {
00575               printf("\n\n%d iterations with %d client threads.\n", 
00576         _iterations, _clients);
00577               printf("Sending %d bytes of client data and %d bytes of server data\n", 
00578         _client_data, _server_data);
00579        }
00580     PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);
00581     PR_STDIO_INIT();
00582 
00583     PR_SetThreadRecycleMode(64);
00584 
00585     ServerStateCVLock = PR_NewLock();
00586     ServerStateCV = PR_NewCondVar(ServerStateCVLock);
00587 
00588     Measure(do_workUK, "server loop user/kernel");
00589 
00590     PR_Cleanup();
00591 
00592        if(failed_already)   
00593               return 1;
00594        else
00595               return 0;
00596 }