Back to index

lightning-sunbird  0.9+nobinonly
servr_uu.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 static void do_work(void);
00099 
00100 /* --- Server state functions --------------------------------------------- */
00101 void
00102 SetServerState(char *waiter, PRInt32 state)
00103 {
00104     PR_Lock(ServerStateCVLock);
00105     ServerState = state;
00106     PR_NotifyCondVar(ServerStateCV);
00107 
00108        if (debug_mode) DPRINTF("\t%s changed state to %d\n", waiter, state);
00109 
00110     PR_Unlock(ServerStateCVLock);
00111 }
00112 
00113 int
00114 WaitServerState(char *waiter, PRInt32 state)
00115 {
00116     PRInt32 rv;
00117 
00118     PR_Lock(ServerStateCVLock);
00119 
00120     if (debug_mode) DPRINTF("\t%s waiting for state %d\n", waiter, state);
00121 
00122     while(!(ServerState & state))
00123         PR_WaitCondVar(ServerStateCV, PR_INTERVAL_NO_TIMEOUT);
00124     rv = ServerState;
00125 
00126     if (debug_mode) DPRINTF("\t%s resuming from wait for state %d; state now %d\n", 
00127         waiter, state, ServerState);
00128     PR_Unlock(ServerStateCVLock);
00129 
00130     return rv;
00131 }
00132 
00133 /* --- Server Functions ------------------------------------------- */
00134 
00135 PRLock *workerThreadsLock;
00136 PRInt32 workerThreads;
00137 PRInt32 workerThreadsBusy;
00138 
00139 void
00140 WorkerThreadFunc(void *_listenSock)
00141 {
00142     PRFileDesc *listenSock = (PRFileDesc *)_listenSock;
00143     PRInt32 bytesRead;
00144     PRInt32 bytesWritten;
00145     char *dataBuf;
00146     char *sendBuf;
00147 
00148     if (debug_mode) DPRINTF("\tServer buffer is %d bytes; %d data, %d netaddrs\n",
00149             _client_data+(2*sizeof(PRNetAddr))+32, _client_data, (2*sizeof(PRNetAddr))+32);
00150     dataBuf = (char *)PR_MALLOC(_client_data + 2*sizeof(PRNetAddr) + 32);
00151     if (!dataBuf)
00152         if (debug_mode) printf("\tServer could not malloc space!?\n");
00153     sendBuf = (char *)PR_MALLOC(_server_data *sizeof(char));
00154     if (!sendBuf)
00155         if (debug_mode) printf("\tServer could not malloc space!?\n");
00156 
00157     if (debug_mode) DPRINTF("\tServer worker thread running\n");
00158 
00159     while(1) {
00160         PRInt32 bytesToRead = _client_data;
00161         PRInt32 bytesToWrite = _server_data;
00162         PRFileDesc *newSock;
00163         PRNetAddr *rAddr;
00164         PRInt32 loops = 0;
00165 
00166         loops++;
00167 
00168         if (debug_mode) DPRINTF("\tServer thread going into accept\n");
00169 
00170         bytesRead = PR_AcceptRead(listenSock, 
00171                                   &newSock,
00172                                   &rAddr,
00173                                   dataBuf,
00174                                   bytesToRead,
00175                                   PR_INTERVAL_NO_TIMEOUT);
00176 
00177         if (bytesRead < 0) {
00178             if (debug_mode) printf("\tServer error in accept (%d)\n", bytesRead);
00179             continue;
00180         }
00181 
00182         if (debug_mode) DPRINTF("\tServer accepted connection (%d bytes)\n", bytesRead);
00183         
00184         PR_AtomicIncrement(&workerThreadsBusy);
00185         if (workerThreadsBusy == workerThreads) {
00186 
00187             PR_Lock(workerThreadsLock);
00188             if (workerThreadsBusy == workerThreads) {
00189                 PRThread *WorkerThread;
00190 
00191                 WorkerThread = PR_CreateThread(
00192                                   PR_SYSTEM_THREAD,
00193                                   WorkerThreadFunc,
00194                                   listenSock,
00195                                   PR_PRIORITY_NORMAL,
00196                                   ServerScope,
00197                                   PR_UNJOINABLE_THREAD,
00198                                   THREAD_STACKSIZE);
00199 
00200                 if (!WorkerThread) {
00201                     if (debug_mode) printf("Error creating client thread %d\n", workerThreads);
00202                 } else {
00203                     PR_AtomicIncrement(&workerThreads);
00204                     if (debug_mode) DPRINTF("\tServer creates worker (%d)\n", workerThreads);
00205                 }
00206             }
00207             PR_Unlock(workerThreadsLock);
00208         }
00209  
00210         bytesToRead -= bytesRead;
00211         while (bytesToRead) {
00212             bytesRead = PR_Recv(newSock, 
00213                                 dataBuf, 
00214                                 bytesToRead, 
00215                                 0, 
00216                                 PR_INTERVAL_NO_TIMEOUT);
00217             if (bytesRead < 0) {
00218                 if (debug_mode) printf("\tServer error receiving data (%d)\n", bytesRead);
00219                 continue;
00220             }
00221             if (debug_mode) DPRINTF("\tServer received %d bytes\n", bytesRead);
00222         }
00223 
00224         bytesWritten = PR_Send(newSock,
00225                                sendBuf, 
00226                                bytesToWrite, 
00227                                0, 
00228                                PR_INTERVAL_NO_TIMEOUT);
00229         if (bytesWritten != _server_data) {
00230             if (debug_mode) printf("\tError sending data to client (%d, %d)\n", 
00231                 bytesWritten, PR_GetOSError());
00232         } else {
00233             if (debug_mode) DPRINTF("\tServer sent %d bytes\n", bytesWritten);
00234         } 
00235 
00236         PR_Close(newSock);
00237         PR_AtomicDecrement(&workerThreadsBusy);
00238     }
00239 }
00240 
00241 PRFileDesc *
00242 ServerSetup(void)
00243 {
00244     PRFileDesc *listenSocket;
00245     PRSocketOptionData sockOpt;
00246     PRNetAddr serverAddr;
00247     PRThread *WorkerThread;
00248 
00249     if ( (listenSocket = PR_NewTCPSocket()) == NULL) {
00250         if (debug_mode) printf("\tServer error creating listen socket\n");
00251               else failed_already=1;
00252         return NULL;
00253     }
00254 
00255     sockOpt.option = PR_SockOpt_Reuseaddr;
00256     sockOpt.value.reuse_addr = PR_TRUE;
00257     if ( PR_SetSocketOption(listenSocket, &sockOpt) == PR_FAILURE) {
00258         if (debug_mode) printf("\tServer error setting socket option: OS error %d\n",
00259                 PR_GetOSError());
00260               else failed_already=1;
00261         PR_Close(listenSocket);
00262         return NULL;
00263     }
00264 
00265     memset(&serverAddr, 0, sizeof(PRNetAddr));
00266     serverAddr.inet.family = PR_AF_INET;
00267     serverAddr.inet.port = PR_htons(PORT);
00268     serverAddr.inet.ip = PR_htonl(PR_INADDR_ANY);
00269 
00270     if ( PR_Bind(listenSocket, &serverAddr) == PR_FAILURE) {
00271         if (debug_mode) printf("\tServer error binding to server address: OS error %d\n",
00272                 PR_GetOSError());
00273               else failed_already=1;
00274         PR_Close(listenSocket);
00275         return NULL;
00276     }
00277 
00278     if ( PR_Listen(listenSocket, 128) == PR_FAILURE) {
00279         if (debug_mode) printf("\tServer error listening to server socket\n");
00280               else failed_already=1;
00281         PR_Close(listenSocket);
00282 
00283         return NULL;
00284     }
00285 
00286     /* Create Clients */
00287     workerThreads = 0;
00288     workerThreadsBusy = 0;
00289 
00290     workerThreadsLock = PR_NewLock();
00291 
00292     WorkerThread = PR_CreateThread(
00293                       PR_SYSTEM_THREAD,
00294                       WorkerThreadFunc,
00295                       listenSocket,
00296                       PR_PRIORITY_NORMAL,
00297                       ServerScope,
00298                       PR_UNJOINABLE_THREAD,
00299                       THREAD_STACKSIZE);
00300 
00301     if (!WorkerThread) {
00302         if (debug_mode) printf("error creating working thread\n");
00303         PR_Close(listenSocket);
00304         return NULL;
00305     }
00306     PR_AtomicIncrement(&workerThreads);
00307     if (debug_mode) DPRINTF("\tServer created primordial worker thread\n");
00308 
00309     return listenSocket;
00310 }
00311 
00312 /* The main server loop */
00313 void
00314 ServerThreadFunc(void *unused)
00315 {
00316     PRFileDesc *listenSocket;
00317 
00318     /* Do setup */
00319     listenSocket = ServerSetup();
00320 
00321     if (!listenSocket) {
00322         SetServerState(SERVER, SERVER_STATE_DEAD);
00323     } else {
00324 
00325         if (debug_mode) DPRINTF("\tServer up\n");
00326 
00327         /* Tell clients they can start now. */
00328         SetServerState(SERVER, SERVER_STATE_READY);
00329 
00330         /* Now wait for server death signal */
00331         WaitServerState(SERVER, SERVER_STATE_DYING);
00332 
00333         /* Cleanup */
00334         SetServerState(SERVER, SERVER_STATE_DEAD);
00335     }
00336 }
00337 
00338 /* --- Client Functions ------------------------------------------- */
00339 
00340 PRInt32 numRequests;
00341 PRInt32 numClients;
00342 PRMonitor *clientMonitor;
00343 
00344 void
00345 ClientThreadFunc(void *unused)
00346 {
00347     PRNetAddr serverAddr;
00348     PRFileDesc *clientSocket;
00349     char *sendBuf;
00350     char *recvBuf;
00351     PRInt32 rv;
00352     PRInt32 bytesNeeded;
00353 
00354     sendBuf = (char *)PR_MALLOC(_client_data * sizeof(char));
00355     if (!sendBuf)
00356         if (debug_mode) printf("\tClient could not malloc space!?\n");
00357     recvBuf = (char *)PR_MALLOC(_server_data * sizeof(char));
00358     if (!recvBuf)
00359         if (debug_mode) printf("\tClient could not malloc space!?\n");
00360 
00361     memset(&serverAddr, 0, sizeof(PRNetAddr));
00362     serverAddr.inet.family = PR_AF_INET;
00363     serverAddr.inet.port = PR_htons(PORT);
00364     serverAddr.inet.ip = PR_htonl(PR_INADDR_LOOPBACK);
00365 
00366     while(numRequests > 0) {
00367 
00368         if ( (numRequests % 10) == 0 )
00369             if (debug_mode) printf(".");
00370         if (debug_mode) DPRINTF("\tClient starting request %d\n", numRequests);
00371 
00372         clientSocket = PR_NewTCPSocket();
00373         if (!clientSocket) {
00374             if (debug_mode) printf("Client error creating socket: OS error %d\n",
00375                   PR_GetOSError());
00376             continue;
00377         }
00378 
00379         if (debug_mode) DPRINTF("\tClient connecting\n");
00380 
00381         rv = PR_Connect(clientSocket, 
00382                         &serverAddr,
00383                         PR_INTERVAL_NO_TIMEOUT);
00384         if (!clientSocket) {
00385             if (debug_mode) printf("\tClient error connecting\n");
00386             continue;
00387         }
00388 
00389         if (debug_mode) DPRINTF("\tClient connected\n");
00390 
00391         rv = PR_Send(clientSocket, 
00392                      sendBuf, 
00393                      _client_data, 
00394                      0, 
00395                      PR_INTERVAL_NO_TIMEOUT);
00396         if (rv != _client_data) {
00397             if (debug_mode) printf("Client error sending data (%d)\n", rv);
00398             PR_Close(clientSocket);
00399             continue;
00400         }
00401 
00402         if (debug_mode) DPRINTF("\tClient sent %d bytes\n", rv);
00403 
00404         bytesNeeded = _server_data;
00405         while(bytesNeeded) {
00406             rv = PR_Recv(clientSocket, 
00407                          recvBuf, 
00408                          bytesNeeded, 
00409                          0, 
00410                          PR_INTERVAL_NO_TIMEOUT);
00411             if (rv <= 0) {
00412                 if (debug_mode) printf("Client error receiving data (%d) (%d/%d)\n", 
00413                     rv, (_server_data - bytesNeeded), _server_data);
00414                 break;
00415             }
00416             if (debug_mode) DPRINTF("\tClient received %d bytes; need %d more\n", rv, bytesNeeded - rv);
00417             bytesNeeded -= rv;
00418         }
00419 
00420         PR_Close(clientSocket);
00421  
00422         PR_AtomicDecrement(&numRequests);
00423     }
00424 
00425     PR_EnterMonitor(clientMonitor);
00426     --numClients;
00427     PR_Notify(clientMonitor);
00428     PR_ExitMonitor(clientMonitor);
00429 
00430     PR_DELETE(sendBuf);
00431     PR_DELETE(recvBuf);
00432 }
00433 
00434 void
00435 RunClients(void)
00436 {
00437     PRInt32 index;
00438 
00439     numRequests = _iterations;
00440     numClients = _clients;
00441     clientMonitor = PR_NewMonitor();
00442 
00443     for (index=0; index<_clients; index++) {
00444         PRThread *clientThread;
00445 
00446   
00447         clientThread = PR_CreateThread(
00448                           PR_USER_THREAD,
00449                           ClientThreadFunc,
00450                           NULL,
00451                           PR_PRIORITY_NORMAL,
00452                           ClientScope,
00453                           PR_UNJOINABLE_THREAD,
00454                           THREAD_STACKSIZE);
00455 
00456         if (!clientThread) {
00457             if (debug_mode) printf("\terror creating client thread %d\n", index);
00458         } else
00459             if (debug_mode) DPRINTF("\tMain created client %d/%d\n", index+1, _clients);
00460 
00461     }
00462 
00463     PR_EnterMonitor(clientMonitor);
00464     while(numClients)
00465         PR_Wait(clientMonitor, PR_INTERVAL_NO_TIMEOUT);
00466     PR_ExitMonitor(clientMonitor);
00467 }
00468 
00469 /* --- Main Function ---------------------------------------------- */
00470 
00471 static
00472 void do_work()
00473 {
00474     PRThread *ServerThread;
00475     PRInt32 state;
00476 
00477     SetServerState(MAIN, SERVER_STATE_STARTUP);
00478     ServerThread = PR_CreateThread(
00479                       PR_USER_THREAD,
00480                       ServerThreadFunc,
00481                       NULL,
00482                       PR_PRIORITY_NORMAL,
00483                       ServerScope,
00484                       PR_JOINABLE_THREAD,
00485                       THREAD_STACKSIZE);
00486     if (!ServerThread) {
00487         if (debug_mode) printf("error creating main server thread\n");
00488         return;
00489     }
00490 
00491     /* Wait for server to be ready */
00492     state = WaitServerState(MAIN, SERVER_STATE_READY|SERVER_STATE_DEAD);
00493 
00494     if (!(state & SERVER_STATE_DEAD)) {
00495         /* Run Test Clients */
00496         RunClients();
00497 
00498         /* Send death signal to server */
00499         SetServerState(MAIN, SERVER_STATE_DYING);
00500     }
00501 
00502     PR_JoinThread(ServerThread);
00503 }
00504 
00505 static void do_workUU(void)
00506 {
00507     ServerScope = PR_LOCAL_THREAD;
00508     ClientScope = PR_LOCAL_THREAD;
00509     do_work();
00510 }
00511 
00512 
00513 
00514 static void Measure(void (*func)(void), const char *msg)
00515 {
00516     PRIntervalTime start, stop;
00517     double d;
00518 
00519     start = PR_IntervalNow();
00520     (*func)();
00521     stop = PR_IntervalNow();
00522 
00523     d = (double)PR_IntervalToMicroseconds(stop - start);
00524 
00525     if (debug_mode) printf("\n%40s: %6.2f usec\n", msg, d / _iterations);
00526 }
00527 
00528 
00529 main(int argc, char **argv)
00530 {
00531        /* The command line argument: -d is used to determine if the test is being run
00532        in debug mode. The regress tool requires only one line output:PASS or FAIL.
00533        All of the printfs associated with this test has been handled with a if (debug_mode)
00534        test.
00535        Usage: test_name -d
00536        */
00537        PLOptStatus os;
00538        PLOptState *opt = PL_CreateOptState(argc, argv, "d:");
00539        while (PL_OPT_EOL != (os = PL_GetNextOpt(opt)))
00540     {
00541               if (PL_OPT_BAD == os) continue;
00542         switch (opt->option)
00543         {
00544         case 'd':  /* debug mode */
00545                      debug_mode = 1;
00546             break;
00547          default:
00548             break;
00549         }
00550     }
00551        PL_DestroyOptState(opt);
00552 
00553  /* main test */
00554     if (debug_mode) {
00555               printf("Enter number of iterations: \n");
00556               scanf("%d", &_iterations);
00557               printf("Enter number of clients   : \n");
00558               scanf("%d", &_clients);
00559               printf("Enter size of client data : \n");
00560               scanf("%d", &_client_data);
00561               printf("Enter size of server data : \n");
00562               scanf("%d", &_server_data);
00563        }
00564        else {
00565               _iterations = 7;
00566               _clients = 7;
00567               _client_data = 100;
00568               _server_data = 100;
00569        }
00570 
00571     if (debug_mode) {
00572               printf("\n\n%d iterations with %d client threads.\n", 
00573         _iterations, _clients);
00574               printf("Sending %d bytes of client data and %d bytes of server data\n", 
00575         _client_data, _server_data);
00576        }
00577     PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);
00578     PR_STDIO_INIT();
00579 
00580     PR_SetThreadRecycleMode(64);
00581 
00582     ServerStateCVLock = PR_NewLock();
00583     ServerStateCV = PR_NewCondVar(ServerStateCVLock);
00584 
00585     Measure(do_workUU, "server loop user/user");
00586 
00587     PR_Cleanup();
00588        
00589        if(failed_already)   
00590               return 1;
00591        else
00592               return 0;
00593     
00594 }