Back to index

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