Upload Tizen:Base source
[toolchains/nspr.git] / mozilla / nsprpub / pr / tests / servr_uu.c
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
4  *
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/
9  *
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.
14  *
15  * The Original Code is the Netscape Portable Runtime (NSPR).
16  *
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.
21  *
22  * Contributor(s):
23  *
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.
35  *
36  * ***** END LICENSE BLOCK ***** */
37
38 /***********************************************************************
39 **
40 ** This server simulates a server running in loopback mode.
41 **
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.
45 **
46 **
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 ***********************************************************************/
56
57 /***********************************************************************
58 ** Includes
59 ***********************************************************************/
60 /* Used to get the command line option */
61 #include "plgetopt.h"
62
63 #include "nspr.h"
64 #include "pprthred.h"
65
66 #include <string.h>
67
68 #define PORT 15004
69 #define THREAD_STACKSIZE 0
70
71 static int _iterations = 1000;
72 static int _clients = 1;
73 static int _client_data = 250;
74 static int _server_data = (8*1024);
75
76 static PRThreadScope ServerScope, ClientScope;
77
78 #define SERVER "Server"
79 #define MAIN   "Main"
80
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;
88
89 #ifdef DEBUGPRINTS
90 #define DPRINTF printf
91 #else
92 #define DPRINTF
93 #endif
94
95 PRIntn failed_already=0;
96 PRIntn debug_mode;
97
98 static void do_work(void);
99
100 /* --- Server state functions --------------------------------------------- */
101 void
102 SetServerState(char *waiter, PRInt32 state)
103 {
104     PR_Lock(ServerStateCVLock);
105     ServerState = state;
106     PR_NotifyCondVar(ServerStateCV);
107
108         if (debug_mode) DPRINTF("\t%s changed state to %d\n", waiter, state);
109
110     PR_Unlock(ServerStateCVLock);
111 }
112
113 int
114 WaitServerState(char *waiter, PRInt32 state)
115 {
116     PRInt32 rv;
117
118     PR_Lock(ServerStateCVLock);
119
120     if (debug_mode) DPRINTF("\t%s waiting for state %d\n", waiter, state);
121
122     while(!(ServerState & state))
123         PR_WaitCondVar(ServerStateCV, PR_INTERVAL_NO_TIMEOUT);
124     rv = ServerState;
125
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);
129
130     return rv;
131 }
132
133 /* --- Server Functions ------------------------------------------- */
134
135 PRLock *workerThreadsLock;
136 PRInt32 workerThreads;
137 PRInt32 workerThreadsBusy;
138
139 void
140 WorkerThreadFunc(void *_listenSock)
141 {
142     PRFileDesc *listenSock = (PRFileDesc *)_listenSock;
143     PRInt32 bytesRead;
144     PRInt32 bytesWritten;
145     char *dataBuf;
146     char *sendBuf;
147
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");
156
157     if (debug_mode) DPRINTF("\tServer worker thread running\n");
158
159     while(1) {
160         PRInt32 bytesToRead = _client_data;
161         PRInt32 bytesToWrite = _server_data;
162         PRFileDesc *newSock;
163         PRNetAddr *rAddr;
164         PRInt32 loops = 0;
165
166         loops++;
167
168         if (debug_mode) DPRINTF("\tServer thread going into accept\n");
169
170         bytesRead = PR_AcceptRead(listenSock, 
171                                   &newSock,
172                                   &rAddr,
173                                   dataBuf,
174                                   bytesToRead,
175                                   PR_INTERVAL_NO_TIMEOUT);
176
177         if (bytesRead < 0) {
178             if (debug_mode) printf("\tServer error in accept (%d)\n", bytesRead);
179             continue;
180         }
181
182         if (debug_mode) DPRINTF("\tServer accepted connection (%d bytes)\n", bytesRead);
183         
184         PR_AtomicIncrement(&workerThreadsBusy);
185 #ifdef SYMBIAN
186         if (workerThreadsBusy == workerThreads && workerThreads<1) {
187 #else
188         if (workerThreadsBusy == workerThreads) {
189 #endif
190
191             PR_Lock(workerThreadsLock);
192             if (workerThreadsBusy == workerThreads) {
193                 PRThread *WorkerThread;
194
195                 WorkerThread = PR_CreateThread(
196                                   PR_SYSTEM_THREAD,
197                                   WorkerThreadFunc,
198                                   listenSock,
199                                   PR_PRIORITY_NORMAL,
200                                   ServerScope,
201                                   PR_UNJOINABLE_THREAD,
202                                   THREAD_STACKSIZE);
203
204                 if (!WorkerThread) {
205                     if (debug_mode) printf("Error creating client thread %d\n", workerThreads);
206                 } else {
207                     PR_AtomicIncrement(&workerThreads);
208                     if (debug_mode) DPRINTF("\tServer creates worker (%d)\n", workerThreads);
209                 }
210             }
211             PR_Unlock(workerThreadsLock);
212         }
213  
214         bytesToRead -= bytesRead;
215         while (bytesToRead) {
216             bytesRead = PR_Recv(newSock, 
217                                 dataBuf, 
218                                 bytesToRead, 
219                                 0, 
220                                 PR_INTERVAL_NO_TIMEOUT);
221             if (bytesRead < 0) {
222                 if (debug_mode) printf("\tServer error receiving data (%d)\n", bytesRead);
223                 continue;
224             }
225             if (debug_mode) DPRINTF("\tServer received %d bytes\n", bytesRead);
226         }
227
228         bytesWritten = PR_Send(newSock,
229                                sendBuf, 
230                                bytesToWrite, 
231                                0, 
232                                PR_INTERVAL_NO_TIMEOUT);
233         if (bytesWritten != _server_data) {
234             if (debug_mode) printf("\tError sending data to client (%d, %d)\n", 
235                 bytesWritten, PR_GetOSError());
236         } else {
237             if (debug_mode) DPRINTF("\tServer sent %d bytes\n", bytesWritten);
238         } 
239
240         PR_Close(newSock);
241         PR_AtomicDecrement(&workerThreadsBusy);
242     }
243 }
244
245 PRFileDesc *
246 ServerSetup(void)
247 {
248     PRFileDesc *listenSocket;
249     PRSocketOptionData sockOpt;
250     PRNetAddr serverAddr;
251     PRThread *WorkerThread;
252
253     if ( (listenSocket = PR_NewTCPSocket()) == NULL) {
254         if (debug_mode) printf("\tServer error creating listen socket\n");
255                 else failed_already=1;
256         return NULL;
257     }
258
259     sockOpt.option = PR_SockOpt_Reuseaddr;
260     sockOpt.value.reuse_addr = PR_TRUE;
261     if ( PR_SetSocketOption(listenSocket, &sockOpt) == PR_FAILURE) {
262         if (debug_mode) printf("\tServer error setting socket option: OS error %d\n",
263                 PR_GetOSError());
264                 else failed_already=1;
265         PR_Close(listenSocket);
266         return NULL;
267     }
268
269     memset(&serverAddr, 0, sizeof(PRNetAddr));
270     serverAddr.inet.family = PR_AF_INET;
271     serverAddr.inet.port = PR_htons(PORT);
272     serverAddr.inet.ip = PR_htonl(PR_INADDR_ANY);
273
274     if ( PR_Bind(listenSocket, &serverAddr) == PR_FAILURE) {
275         if (debug_mode) printf("\tServer error binding to server address: OS error %d\n",
276                 PR_GetOSError());
277                 else failed_already=1;
278         PR_Close(listenSocket);
279         return NULL;
280     }
281
282     if ( PR_Listen(listenSocket, 128) == PR_FAILURE) {
283         if (debug_mode) printf("\tServer error listening to server socket\n");
284                 else failed_already=1;
285         PR_Close(listenSocket);
286
287         return NULL;
288     }
289
290     /* Create Clients */
291     workerThreads = 0;
292     workerThreadsBusy = 0;
293
294     workerThreadsLock = PR_NewLock();
295
296     WorkerThread = PR_CreateThread(
297                       PR_SYSTEM_THREAD,
298                       WorkerThreadFunc,
299                       listenSocket,
300                       PR_PRIORITY_NORMAL,
301                       ServerScope,
302                       PR_UNJOINABLE_THREAD,
303                       THREAD_STACKSIZE);
304
305     if (!WorkerThread) {
306         if (debug_mode) printf("error creating working thread\n");
307         PR_Close(listenSocket);
308         return NULL;
309     }
310     PR_AtomicIncrement(&workerThreads);
311     if (debug_mode) DPRINTF("\tServer created primordial worker thread\n");
312
313     return listenSocket;
314 }
315
316 /* The main server loop */
317 void
318 ServerThreadFunc(void *unused)
319 {
320     PRFileDesc *listenSocket;
321
322     /* Do setup */
323     listenSocket = ServerSetup();
324
325     if (!listenSocket) {
326         SetServerState(SERVER, SERVER_STATE_DEAD);
327     } else {
328
329         if (debug_mode) DPRINTF("\tServer up\n");
330
331         /* Tell clients they can start now. */
332         SetServerState(SERVER, SERVER_STATE_READY);
333
334         /* Now wait for server death signal */
335         WaitServerState(SERVER, SERVER_STATE_DYING);
336
337         /* Cleanup */
338         SetServerState(SERVER, SERVER_STATE_DEAD);
339     }
340 }
341
342 /* --- Client Functions ------------------------------------------- */
343
344 PRInt32 numRequests;
345 PRInt32 numClients;
346 PRMonitor *clientMonitor;
347
348 void
349 ClientThreadFunc(void *unused)
350 {
351     PRNetAddr serverAddr;
352     PRFileDesc *clientSocket;
353     char *sendBuf;
354     char *recvBuf;
355     PRInt32 rv;
356     PRInt32 bytesNeeded;
357
358     sendBuf = (char *)PR_MALLOC(_client_data * sizeof(char));
359     if (!sendBuf)
360         if (debug_mode) printf("\tClient could not malloc space!?\n");
361     recvBuf = (char *)PR_MALLOC(_server_data * sizeof(char));
362     if (!recvBuf)
363         if (debug_mode) printf("\tClient could not malloc space!?\n");
364
365     memset(&serverAddr, 0, sizeof(PRNetAddr));
366     serverAddr.inet.family = PR_AF_INET;
367     serverAddr.inet.port = PR_htons(PORT);
368     serverAddr.inet.ip = PR_htonl(PR_INADDR_LOOPBACK);
369
370     while(numRequests > 0) {
371
372         if ( (numRequests % 10) == 0 )
373             if (debug_mode) printf(".");
374         if (debug_mode) DPRINTF("\tClient starting request %d\n", numRequests);
375
376         clientSocket = PR_NewTCPSocket();
377         if (!clientSocket) {
378             if (debug_mode) printf("Client error creating socket: OS error %d\n",
379                     PR_GetOSError());
380             continue;
381         }
382
383         if (debug_mode) DPRINTF("\tClient connecting\n");
384
385         rv = PR_Connect(clientSocket, 
386                         &serverAddr,
387                         PR_INTERVAL_NO_TIMEOUT);
388         if (!clientSocket) {
389             if (debug_mode) printf("\tClient error connecting\n");
390             continue;
391         }
392
393         if (debug_mode) DPRINTF("\tClient connected\n");
394
395         rv = PR_Send(clientSocket, 
396                      sendBuf, 
397                      _client_data, 
398                      0, 
399                      PR_INTERVAL_NO_TIMEOUT);
400         if (rv != _client_data) {
401             if (debug_mode) printf("Client error sending data (%d)\n", rv);
402             PR_Close(clientSocket);
403             continue;
404         }
405
406         if (debug_mode) DPRINTF("\tClient sent %d bytes\n", rv);
407
408         bytesNeeded = _server_data;
409         while(bytesNeeded) {
410             rv = PR_Recv(clientSocket, 
411                          recvBuf, 
412                          bytesNeeded, 
413                          0, 
414                          PR_INTERVAL_NO_TIMEOUT);
415             if (rv <= 0) {
416                 if (debug_mode) printf("Client error receiving data (%d) (%d/%d)\n", 
417                     rv, (_server_data - bytesNeeded), _server_data);
418                 break;
419             }
420             if (debug_mode) DPRINTF("\tClient received %d bytes; need %d more\n", rv, bytesNeeded - rv);
421             bytesNeeded -= rv;
422         }
423
424         PR_Close(clientSocket);
425  
426         PR_AtomicDecrement(&numRequests);
427     }
428
429     PR_EnterMonitor(clientMonitor);
430     --numClients;
431     PR_Notify(clientMonitor);
432     PR_ExitMonitor(clientMonitor);
433
434     PR_DELETE(sendBuf);
435     PR_DELETE(recvBuf);
436 }
437
438 void
439 RunClients(void)
440 {
441     PRInt32 index;
442
443     numRequests = _iterations;
444     numClients = _clients;
445     clientMonitor = PR_NewMonitor();
446
447     for (index=0; index<_clients; index++) {
448         PRThread *clientThread;
449
450   
451         clientThread = PR_CreateThread(
452                           PR_USER_THREAD,
453                           ClientThreadFunc,
454                           NULL,
455                           PR_PRIORITY_NORMAL,
456                           ClientScope,
457                           PR_UNJOINABLE_THREAD,
458                           THREAD_STACKSIZE);
459
460         if (!clientThread) {
461             if (debug_mode) printf("\terror creating client thread %d\n", index);
462         } else
463             if (debug_mode) DPRINTF("\tMain created client %d/%d\n", index+1, _clients);
464
465     }
466
467     PR_EnterMonitor(clientMonitor);
468     while(numClients)
469         PR_Wait(clientMonitor, PR_INTERVAL_NO_TIMEOUT);
470     PR_ExitMonitor(clientMonitor);
471 }
472
473 /* --- Main Function ---------------------------------------------- */
474
475 static
476 void do_work()
477 {
478     PRThread *ServerThread;
479     PRInt32 state;
480
481     SetServerState(MAIN, SERVER_STATE_STARTUP);
482     ServerThread = PR_CreateThread(
483                       PR_USER_THREAD,
484                       ServerThreadFunc,
485                       NULL,
486                       PR_PRIORITY_NORMAL,
487                       ServerScope,
488                       PR_JOINABLE_THREAD,
489                       THREAD_STACKSIZE);
490     if (!ServerThread) {
491         if (debug_mode) printf("error creating main server thread\n");
492         return;
493     }
494
495     /* Wait for server to be ready */
496     state = WaitServerState(MAIN, SERVER_STATE_READY|SERVER_STATE_DEAD);
497
498     if (!(state & SERVER_STATE_DEAD)) {
499         /* Run Test Clients */
500         RunClients();
501
502         /* Send death signal to server */
503         SetServerState(MAIN, SERVER_STATE_DYING);
504     }
505
506     PR_JoinThread(ServerThread);
507 }
508
509 static void do_workUU(void)
510 {
511     ServerScope = PR_LOCAL_THREAD;
512     ClientScope = PR_LOCAL_THREAD;
513     do_work();
514 }
515
516
517
518 static void Measure(void (*func)(void), const char *msg)
519 {
520     PRIntervalTime start, stop;
521     double d;
522
523     start = PR_IntervalNow();
524     (*func)();
525     stop = PR_IntervalNow();
526
527     d = (double)PR_IntervalToMicroseconds(stop - start);
528
529     if (debug_mode) printf("\n%40s: %6.2f usec\n", msg, d / _iterations);
530 }
531
532
533 int main(int argc, char **argv)
534 {
535         /* The command line argument: -d is used to determine if the test is being run
536         in debug mode. The regress tool requires only one line output:PASS or FAIL.
537         All of the printfs associated with this test has been handled with a if (debug_mode)
538         test.
539         Usage: test_name -d
540         */
541         PLOptStatus os;
542         PLOptState *opt = PL_CreateOptState(argc, argv, "d:");
543         while (PL_OPT_EOL != (os = PL_GetNextOpt(opt)))
544     {
545                 if (PL_OPT_BAD == os) continue;
546         switch (opt->option)
547         {
548         case 'd':  /* debug mode */
549                         debug_mode = 1;
550             break;
551          default:
552             break;
553         }
554     }
555         PL_DestroyOptState(opt);
556
557  /* main test */
558 #ifndef SYMBIAN
559     if (debug_mode) {
560                 printf("Enter number of iterations: \n");
561                 scanf("%d", &_iterations);
562                 printf("Enter number of clients   : \n");
563                 scanf("%d", &_clients);
564                 printf("Enter size of client data : \n");
565                 scanf("%d", &_client_data);
566                 printf("Enter size of server data : \n");
567                 scanf("%d", &_server_data);
568         }
569         else 
570 #endif
571         {
572                 _iterations = 7;
573                 _clients = 7;
574                 _client_data = 100;
575                 _server_data = 100;
576         }
577
578     if (debug_mode) {
579                 printf("\n\n%d iterations with %d client threads.\n", 
580         _iterations, _clients);
581                 printf("Sending %d bytes of client data and %d bytes of server data\n", 
582         _client_data, _server_data);
583         }
584     PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);
585     PR_STDIO_INIT();
586
587     PR_SetThreadRecycleMode(64);
588
589     ServerStateCVLock = PR_NewLock();
590     ServerStateCV = PR_NewCondVar(ServerStateCVLock);
591
592     Measure(do_workUU, "server loop user/user");
593
594     PR_Cleanup();
595         
596         if(failed_already)      
597                 return 1;
598         else
599                 return 0;
600     
601 }