nspr: import 3.0 RC1 cutoff from CVS
[mozilla-nspr.git] / nsprpub / pr / tests / servr_uu.c
blob020fadf669aba9d536efa738acc600f9e70be079
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* ***** BEGIN LICENSE BLOCK *****
3 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
5 * The contents of this file are subject to the Mozilla Public License Version
6 * 1.1 (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 * http://www.mozilla.org/MPL/
10 * Software distributed under the License is distributed on an "AS IS" basis,
11 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
12 * for the specific language governing rights and limitations under the
13 * License.
15 * The Original Code is the Netscape Portable Runtime (NSPR).
17 * The Initial Developer of the Original Code is
18 * Netscape Communications Corporation.
19 * Portions created by the Initial Developer are Copyright (C) 1998-2000
20 * the Initial Developer. All Rights Reserved.
22 * Contributor(s):
24 * Alternatively, the contents of this file may be used under the terms of
25 * either the GNU General Public License Version 2 or later (the "GPL"), or
26 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
27 * in which case the provisions of the GPL or the LGPL are applicable instead
28 * of those above. If you wish to allow use of your version of this file only
29 * under the terms of either the GPL or the LGPL, and not to allow others to
30 * use your version of this file under the terms of the MPL, indicate your
31 * decision by deleting the provisions above and replace them with the notice
32 * and other provisions required by the GPL or the LGPL. If you do not delete
33 * the provisions above, a recipient may use your version of this file under
34 * the terms of any one of the MPL, the GPL or the LGPL.
36 * ***** END LICENSE BLOCK ***** */
38 /***********************************************************************
40 ** This server simulates a server running in loopback mode.
42 ** The idea is that a single server is created. The server initially creates
43 ** a number of worker threads. Then, with the server running, a number of
44 ** clients are created which start requesting service from the server.
47 ** Modification History:
48 ** 19-May-97 AGarcia- Converted the test to accomodate the debug_mode flag.
49 ** The debug mode will print all of the printfs associated with this test.
50 ** The regress mode will be the default mode. Since the regress tool limits
51 ** the output to a one line status:PASS or FAIL,all of the printf statements
52 ** have been handled with an if (debug_mode) statement.
53 ** 04-June-97 AGarcia removed the Test_Result function. Regress tool has been updated to
54 ** recognize the return code from tha main program.
55 ***********************************************************************/
57 /***********************************************************************
58 ** Includes
59 ***********************************************************************/
60 /* Used to get the command line option */
61 #include "plgetopt.h"
63 #include "nspr.h"
64 #include "pprthred.h"
66 #include <string.h>
68 #define PORT 15004
69 #define THREAD_STACKSIZE 0
71 static int _iterations = 1000;
72 static int _clients = 1;
73 static int _client_data = 250;
74 static int _server_data = (8*1024);
76 static PRThreadScope ServerScope, ClientScope;
78 #define SERVER "Server"
79 #define MAIN "Main"
81 #define SERVER_STATE_STARTUP 0
82 #define SERVER_STATE_READY 1
83 #define SERVER_STATE_DYING 2
84 #define SERVER_STATE_DEAD 4
85 int ServerState;
86 PRLock *ServerStateCVLock;
87 PRCondVar *ServerStateCV;
89 #ifdef DEBUGPRINTS
90 #define DPRINTF printf
91 #else
92 #define DPRINTF
93 #endif
95 PRIntn failed_already=0;
96 PRIntn debug_mode;
98 static void do_work(void);
100 /* --- Server state functions --------------------------------------------- */
101 void
102 SetServerState(char *waiter, PRInt32 state)
104 PR_Lock(ServerStateCVLock);
105 ServerState = state;
106 PR_NotifyCondVar(ServerStateCV);
108 if (debug_mode) DPRINTF("\t%s changed state to %d\n", waiter, state);
110 PR_Unlock(ServerStateCVLock);
114 WaitServerState(char *waiter, PRInt32 state)
116 PRInt32 rv;
118 PR_Lock(ServerStateCVLock);
120 if (debug_mode) DPRINTF("\t%s waiting for state %d\n", waiter, state);
122 while(!(ServerState & state))
123 PR_WaitCondVar(ServerStateCV, PR_INTERVAL_NO_TIMEOUT);
124 rv = ServerState;
126 if (debug_mode) DPRINTF("\t%s resuming from wait for state %d; state now %d\n",
127 waiter, state, ServerState);
128 PR_Unlock(ServerStateCVLock);
130 return rv;
133 /* --- Server Functions ------------------------------------------- */
135 PRLock *workerThreadsLock;
136 PRInt32 workerThreads;
137 PRInt32 workerThreadsBusy;
139 void
140 WorkerThreadFunc(void *_listenSock)
142 PRFileDesc *listenSock = (PRFileDesc *)_listenSock;
143 PRInt32 bytesRead;
144 PRInt32 bytesWritten;
145 char *dataBuf;
146 char *sendBuf;
148 if (debug_mode) DPRINTF("\tServer buffer is %d bytes; %d data, %d netaddrs\n",
149 _client_data+(2*sizeof(PRNetAddr))+32, _client_data, (2*sizeof(PRNetAddr))+32);
150 dataBuf = (char *)PR_MALLOC(_client_data + 2*sizeof(PRNetAddr) + 32);
151 if (!dataBuf)
152 if (debug_mode) printf("\tServer could not malloc space!?\n");
153 sendBuf = (char *)PR_MALLOC(_server_data *sizeof(char));
154 if (!sendBuf)
155 if (debug_mode) printf("\tServer could not malloc space!?\n");
157 if (debug_mode) DPRINTF("\tServer worker thread running\n");
159 while(1) {
160 PRInt32 bytesToRead = _client_data;
161 PRInt32 bytesToWrite = _server_data;
162 PRFileDesc *newSock;
163 PRNetAddr *rAddr;
164 PRInt32 loops = 0;
166 loops++;
168 if (debug_mode) DPRINTF("\tServer thread going into accept\n");
170 bytesRead = PR_AcceptRead(listenSock,
171 &newSock,
172 &rAddr,
173 dataBuf,
174 bytesToRead,
175 PR_INTERVAL_NO_TIMEOUT);
177 if (bytesRead < 0) {
178 if (debug_mode) printf("\tServer error in accept (%d)\n", bytesRead);
179 continue;
182 if (debug_mode) DPRINTF("\tServer accepted connection (%d bytes)\n", bytesRead);
184 PR_AtomicIncrement(&workerThreadsBusy);
185 if (workerThreadsBusy == workerThreads) {
187 PR_Lock(workerThreadsLock);
188 if (workerThreadsBusy == workerThreads) {
189 PRThread *WorkerThread;
191 WorkerThread = PR_CreateThread(
192 PR_SYSTEM_THREAD,
193 WorkerThreadFunc,
194 listenSock,
195 PR_PRIORITY_NORMAL,
196 ServerScope,
197 PR_UNJOINABLE_THREAD,
198 THREAD_STACKSIZE);
200 if (!WorkerThread) {
201 if (debug_mode) printf("Error creating client thread %d\n", workerThreads);
202 } else {
203 PR_AtomicIncrement(&workerThreads);
204 if (debug_mode) DPRINTF("\tServer creates worker (%d)\n", workerThreads);
207 PR_Unlock(workerThreadsLock);
210 bytesToRead -= bytesRead;
211 while (bytesToRead) {
212 bytesRead = PR_Recv(newSock,
213 dataBuf,
214 bytesToRead,
216 PR_INTERVAL_NO_TIMEOUT);
217 if (bytesRead < 0) {
218 if (debug_mode) printf("\tServer error receiving data (%d)\n", bytesRead);
219 continue;
221 if (debug_mode) DPRINTF("\tServer received %d bytes\n", bytesRead);
224 bytesWritten = PR_Send(newSock,
225 sendBuf,
226 bytesToWrite,
228 PR_INTERVAL_NO_TIMEOUT);
229 if (bytesWritten != _server_data) {
230 if (debug_mode) printf("\tError sending data to client (%d, %d)\n",
231 bytesWritten, PR_GetOSError());
232 } else {
233 if (debug_mode) DPRINTF("\tServer sent %d bytes\n", bytesWritten);
236 PR_Close(newSock);
237 PR_AtomicDecrement(&workerThreadsBusy);
241 PRFileDesc *
242 ServerSetup(void)
244 PRFileDesc *listenSocket;
245 PRSocketOptionData sockOpt;
246 PRNetAddr serverAddr;
247 PRThread *WorkerThread;
249 if ( (listenSocket = PR_NewTCPSocket()) == NULL) {
250 if (debug_mode) printf("\tServer error creating listen socket\n");
251 else failed_already=1;
252 return NULL;
255 sockOpt.option = PR_SockOpt_Reuseaddr;
256 sockOpt.value.reuse_addr = PR_TRUE;
257 if ( PR_SetSocketOption(listenSocket, &sockOpt) == PR_FAILURE) {
258 if (debug_mode) printf("\tServer error setting socket option: OS error %d\n",
259 PR_GetOSError());
260 else failed_already=1;
261 PR_Close(listenSocket);
262 return NULL;
265 memset(&serverAddr, 0, sizeof(PRNetAddr));
266 serverAddr.inet.family = PR_AF_INET;
267 serverAddr.inet.port = PR_htons(PORT);
268 serverAddr.inet.ip = PR_htonl(PR_INADDR_ANY);
270 if ( PR_Bind(listenSocket, &serverAddr) == PR_FAILURE) {
271 if (debug_mode) printf("\tServer error binding to server address: OS error %d\n",
272 PR_GetOSError());
273 else failed_already=1;
274 PR_Close(listenSocket);
275 return NULL;
278 if ( PR_Listen(listenSocket, 128) == PR_FAILURE) {
279 if (debug_mode) printf("\tServer error listening to server socket\n");
280 else failed_already=1;
281 PR_Close(listenSocket);
283 return NULL;
286 /* Create Clients */
287 workerThreads = 0;
288 workerThreadsBusy = 0;
290 workerThreadsLock = PR_NewLock();
292 WorkerThread = PR_CreateThread(
293 PR_SYSTEM_THREAD,
294 WorkerThreadFunc,
295 listenSocket,
296 PR_PRIORITY_NORMAL,
297 ServerScope,
298 PR_UNJOINABLE_THREAD,
299 THREAD_STACKSIZE);
301 if (!WorkerThread) {
302 if (debug_mode) printf("error creating working thread\n");
303 PR_Close(listenSocket);
304 return NULL;
306 PR_AtomicIncrement(&workerThreads);
307 if (debug_mode) DPRINTF("\tServer created primordial worker thread\n");
309 return listenSocket;
312 /* The main server loop */
313 void
314 ServerThreadFunc(void *unused)
316 PRFileDesc *listenSocket;
318 /* Do setup */
319 listenSocket = ServerSetup();
321 if (!listenSocket) {
322 SetServerState(SERVER, SERVER_STATE_DEAD);
323 } else {
325 if (debug_mode) DPRINTF("\tServer up\n");
327 /* Tell clients they can start now. */
328 SetServerState(SERVER, SERVER_STATE_READY);
330 /* Now wait for server death signal */
331 WaitServerState(SERVER, SERVER_STATE_DYING);
333 /* Cleanup */
334 SetServerState(SERVER, SERVER_STATE_DEAD);
338 /* --- Client Functions ------------------------------------------- */
340 PRInt32 numRequests;
341 PRInt32 numClients;
342 PRMonitor *clientMonitor;
344 void
345 ClientThreadFunc(void *unused)
347 PRNetAddr serverAddr;
348 PRFileDesc *clientSocket;
349 char *sendBuf;
350 char *recvBuf;
351 PRInt32 rv;
352 PRInt32 bytesNeeded;
354 sendBuf = (char *)PR_MALLOC(_client_data * sizeof(char));
355 if (!sendBuf)
356 if (debug_mode) printf("\tClient could not malloc space!?\n");
357 recvBuf = (char *)PR_MALLOC(_server_data * sizeof(char));
358 if (!recvBuf)
359 if (debug_mode) printf("\tClient could not malloc space!?\n");
361 memset(&serverAddr, 0, sizeof(PRNetAddr));
362 serverAddr.inet.family = PR_AF_INET;
363 serverAddr.inet.port = PR_htons(PORT);
364 serverAddr.inet.ip = PR_htonl(PR_INADDR_LOOPBACK);
366 while(numRequests > 0) {
368 if ( (numRequests % 10) == 0 )
369 if (debug_mode) printf(".");
370 if (debug_mode) DPRINTF("\tClient starting request %d\n", numRequests);
372 clientSocket = PR_NewTCPSocket();
373 if (!clientSocket) {
374 if (debug_mode) printf("Client error creating socket: OS error %d\n",
375 PR_GetOSError());
376 continue;
379 if (debug_mode) DPRINTF("\tClient connecting\n");
381 rv = PR_Connect(clientSocket,
382 &serverAddr,
383 PR_INTERVAL_NO_TIMEOUT);
384 if (!clientSocket) {
385 if (debug_mode) printf("\tClient error connecting\n");
386 continue;
389 if (debug_mode) DPRINTF("\tClient connected\n");
391 rv = PR_Send(clientSocket,
392 sendBuf,
393 _client_data,
395 PR_INTERVAL_NO_TIMEOUT);
396 if (rv != _client_data) {
397 if (debug_mode) printf("Client error sending data (%d)\n", rv);
398 PR_Close(clientSocket);
399 continue;
402 if (debug_mode) DPRINTF("\tClient sent %d bytes\n", rv);
404 bytesNeeded = _server_data;
405 while(bytesNeeded) {
406 rv = PR_Recv(clientSocket,
407 recvBuf,
408 bytesNeeded,
410 PR_INTERVAL_NO_TIMEOUT);
411 if (rv <= 0) {
412 if (debug_mode) printf("Client error receiving data (%d) (%d/%d)\n",
413 rv, (_server_data - bytesNeeded), _server_data);
414 break;
416 if (debug_mode) DPRINTF("\tClient received %d bytes; need %d more\n", rv, bytesNeeded - rv);
417 bytesNeeded -= rv;
420 PR_Close(clientSocket);
422 PR_AtomicDecrement(&numRequests);
425 PR_EnterMonitor(clientMonitor);
426 --numClients;
427 PR_Notify(clientMonitor);
428 PR_ExitMonitor(clientMonitor);
430 PR_DELETE(sendBuf);
431 PR_DELETE(recvBuf);
434 void
435 RunClients(void)
437 PRInt32 index;
439 numRequests = _iterations;
440 numClients = _clients;
441 clientMonitor = PR_NewMonitor();
443 for (index=0; index<_clients; index++) {
444 PRThread *clientThread;
447 clientThread = PR_CreateThread(
448 PR_USER_THREAD,
449 ClientThreadFunc,
450 NULL,
451 PR_PRIORITY_NORMAL,
452 ClientScope,
453 PR_UNJOINABLE_THREAD,
454 THREAD_STACKSIZE);
456 if (!clientThread) {
457 if (debug_mode) printf("\terror creating client thread %d\n", index);
458 } else
459 if (debug_mode) DPRINTF("\tMain created client %d/%d\n", index+1, _clients);
463 PR_EnterMonitor(clientMonitor);
464 while(numClients)
465 PR_Wait(clientMonitor, PR_INTERVAL_NO_TIMEOUT);
466 PR_ExitMonitor(clientMonitor);
469 /* --- Main Function ---------------------------------------------- */
471 static
472 void do_work()
474 PRThread *ServerThread;
475 PRInt32 state;
477 SetServerState(MAIN, SERVER_STATE_STARTUP);
478 ServerThread = PR_CreateThread(
479 PR_USER_THREAD,
480 ServerThreadFunc,
481 NULL,
482 PR_PRIORITY_NORMAL,
483 ServerScope,
484 PR_JOINABLE_THREAD,
485 THREAD_STACKSIZE);
486 if (!ServerThread) {
487 if (debug_mode) printf("error creating main server thread\n");
488 return;
491 /* Wait for server to be ready */
492 state = WaitServerState(MAIN, SERVER_STATE_READY|SERVER_STATE_DEAD);
494 if (!(state & SERVER_STATE_DEAD)) {
495 /* Run Test Clients */
496 RunClients();
498 /* Send death signal to server */
499 SetServerState(MAIN, SERVER_STATE_DYING);
502 PR_JoinThread(ServerThread);
505 static void do_workUU(void)
507 ServerScope = PR_LOCAL_THREAD;
508 ClientScope = PR_LOCAL_THREAD;
509 do_work();
514 static void Measure(void (*func)(void), const char *msg)
516 PRIntervalTime start, stop;
517 double d;
519 start = PR_IntervalNow();
520 (*func)();
521 stop = PR_IntervalNow();
523 d = (double)PR_IntervalToMicroseconds(stop - start);
525 if (debug_mode) printf("\n%40s: %6.2f usec\n", msg, d / _iterations);
529 main(int argc, char **argv)
531 /* The command line argument: -d is used to determine if the test is being run
532 in debug mode. The regress tool requires only one line output:PASS or FAIL.
533 All of the printfs associated with this test has been handled with a if (debug_mode)
534 test.
535 Usage: test_name -d
537 PLOptStatus os;
538 PLOptState *opt = PL_CreateOptState(argc, argv, "d:");
539 while (PL_OPT_EOL != (os = PL_GetNextOpt(opt)))
541 if (PL_OPT_BAD == os) continue;
542 switch (opt->option)
544 case 'd': /* debug mode */
545 debug_mode = 1;
546 break;
547 default:
548 break;
551 PL_DestroyOptState(opt);
553 /* main test */
554 if (debug_mode) {
555 printf("Enter number of iterations: \n");
556 scanf("%d", &_iterations);
557 printf("Enter number of clients : \n");
558 scanf("%d", &_clients);
559 printf("Enter size of client data : \n");
560 scanf("%d", &_client_data);
561 printf("Enter size of server data : \n");
562 scanf("%d", &_server_data);
564 else {
565 _iterations = 7;
566 _clients = 7;
567 _client_data = 100;
568 _server_data = 100;
571 if (debug_mode) {
572 printf("\n\n%d iterations with %d client threads.\n",
573 _iterations, _clients);
574 printf("Sending %d bytes of client data and %d bytes of server data\n",
575 _client_data, _server_data);
577 PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);
578 PR_STDIO_INIT();
580 PR_SetThreadRecycleMode(64);
582 ServerStateCVLock = PR_NewLock();
583 ServerStateCV = PR_NewCondVar(ServerStateCVLock);
585 Measure(do_workUU, "server loop user/user");
587 PR_Cleanup();
589 if(failed_already)
590 return 1;
591 else
592 return 0;