Upload Tizen:Base source
[toolchains/nspr.git] / mozilla / nsprpub / pr / tests / servr_ku.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             PR_Lock(workerThreadsLock);
191             if (workerThreadsBusy == workerThreads) {
192                 PRThread *WorkerThread;
193
194                 WorkerThread = PR_CreateThread(
195                                   PR_SYSTEM_THREAD,
196                                   WorkerThreadFunc,
197                                   listenSock,
198                                   PR_PRIORITY_NORMAL,
199                                   ServerScope,
200                                   PR_UNJOINABLE_THREAD,
201                                   THREAD_STACKSIZE);
202
203                 if (!WorkerThread) {
204                     if (debug_mode) printf("Error creating client thread %d\n", workerThreads);
205                 } else {
206                     PR_AtomicIncrement(&workerThreads);
207                     if (debug_mode) DPRINTF("\tServer creates worker (%d)\n", workerThreads);
208                 }
209             }
210             PR_Unlock(workerThreadsLock);
211         }
212  
213         bytesToRead -= bytesRead;
214         while (bytesToRead) {
215             bytesRead = PR_Recv(newSock, 
216                                 dataBuf, 
217                                 bytesToRead, 
218                                 0, 
219                                 PR_INTERVAL_NO_TIMEOUT);
220             if (bytesRead < 0) {
221                 if (debug_mode) printf("\tServer error receiving data (%d)\n", bytesRead);
222                 continue;
223             }
224             if (debug_mode) DPRINTF("\tServer received %d bytes\n", bytesRead);
225         }
226
227         bytesWritten = PR_Send(newSock,
228                                sendBuf, 
229                                bytesToWrite, 
230                                0, 
231                                PR_INTERVAL_NO_TIMEOUT);
232         if (bytesWritten != _server_data) {
233             if (debug_mode) printf("\tError sending data to client (%d, %d)\n", 
234                 bytesWritten, PR_GetOSError());
235         } else {
236             if (debug_mode) DPRINTF("\tServer sent %d bytes\n", bytesWritten);
237         }
238
239         PR_Close(newSock);
240         PR_AtomicDecrement(&workerThreadsBusy);
241     }
242 }
243
244 PRFileDesc *
245 ServerSetup(void)
246 {
247     PRFileDesc *listenSocket;
248     PRSocketOptionData sockOpt;
249     PRNetAddr serverAddr;
250     PRThread *WorkerThread;
251
252     if ( (listenSocket = PR_NewTCPSocket()) == NULL) {
253         if (debug_mode) printf("\tServer error creating listen socket\n");
254                 else failed_already=1;
255         return NULL;
256     }
257
258     sockOpt.option = PR_SockOpt_Reuseaddr;
259     sockOpt.value.reuse_addr = PR_TRUE;
260     if ( PR_SetSocketOption(listenSocket, &sockOpt) == PR_FAILURE) {
261         if (debug_mode) printf("\tServer error setting socket option: OS error %d\n",
262                 PR_GetOSError());
263                 else failed_already=1;
264         PR_Close(listenSocket);
265         return NULL;
266     }
267
268     memset(&serverAddr, 0, sizeof(PRNetAddr));
269     serverAddr.inet.family = PR_AF_INET;
270     serverAddr.inet.port = PR_htons(PORT);
271     serverAddr.inet.ip = PR_htonl(PR_INADDR_ANY);
272
273     if ( PR_Bind(listenSocket, &serverAddr) == PR_FAILURE) {
274         if (debug_mode) printf("\tServer error binding to server address: OS error %d\n",
275                 PR_GetOSError());
276                 else failed_already=1;
277         PR_Close(listenSocket);
278         return NULL;
279     }
280
281     if ( PR_Listen(listenSocket, 128) == PR_FAILURE) {
282         if (debug_mode) printf("\tServer error listening to server socket\n");
283                 else failed_already=1;
284         PR_Close(listenSocket);
285
286         return NULL;
287     }
288
289     /* Create Clients */
290     workerThreads = 0;
291     workerThreadsBusy = 0;
292
293     workerThreadsLock = PR_NewLock();
294
295     WorkerThread = PR_CreateThread(
296                       PR_SYSTEM_THREAD,
297                       WorkerThreadFunc,
298                       listenSocket,
299                       PR_PRIORITY_NORMAL,
300                       ServerScope,
301                       PR_UNJOINABLE_THREAD,
302                       THREAD_STACKSIZE);
303
304     if (!WorkerThread) {
305         if (debug_mode) printf("error creating working thread\n");
306         PR_Close(listenSocket);
307         return NULL;
308     }
309     PR_AtomicIncrement(&workerThreads);
310     if (debug_mode) DPRINTF("\tServer created primordial worker thread\n");
311
312     return listenSocket;
313 }
314
315 /* The main server loop */
316 void
317 ServerThreadFunc(void *unused)
318 {
319     PRFileDesc *listenSocket;
320
321     /* Do setup */
322     listenSocket = ServerSetup();
323
324     if (!listenSocket) {
325         SetServerState(SERVER, SERVER_STATE_DEAD);
326     } else {
327
328         if (debug_mode) DPRINTF("\tServer up\n");
329
330         /* Tell clients they can start now. */
331         SetServerState(SERVER, SERVER_STATE_READY);
332
333         /* Now wait for server death signal */
334         WaitServerState(SERVER, SERVER_STATE_DYING);
335
336         /* Cleanup */
337         SetServerState(SERVER, SERVER_STATE_DEAD);
338     }
339 }
340
341 /* --- Client Functions ------------------------------------------- */
342
343 PRInt32 numRequests;
344 PRInt32 numClients;
345 PRMonitor *clientMonitor;
346
347 void
348 ClientThreadFunc(void *unused)
349 {
350     PRNetAddr serverAddr;
351     PRFileDesc *clientSocket;
352     char *sendBuf;
353     char *recvBuf;
354     PRInt32 rv;
355     PRInt32 bytesNeeded;
356
357     sendBuf = (char *)PR_MALLOC(_client_data * sizeof(char));
358     if (!sendBuf)
359         if (debug_mode) printf("\tClient could not malloc space!?\n");
360     recvBuf = (char *)PR_MALLOC(_server_data * sizeof(char));
361     if (!recvBuf)
362         if (debug_mode) printf("\tClient could not malloc space!?\n");
363
364     memset(&serverAddr, 0, sizeof(PRNetAddr));
365     serverAddr.inet.family = PR_AF_INET;
366     serverAddr.inet.port = PR_htons(PORT);
367     serverAddr.inet.ip = PR_htonl(PR_INADDR_LOOPBACK);
368
369     while(numRequests > 0) {
370
371         if ( (numRequests % 10) == 0 )
372             if (debug_mode) printf(".");
373         if (debug_mode) DPRINTF("\tClient starting request %d\n", numRequests);
374
375         clientSocket = PR_NewTCPSocket();
376         if (!clientSocket) {
377             if (debug_mode) printf("Client error creating socket: OS error %d\n",
378                     PR_GetOSError());
379             continue;
380         }
381
382         if (debug_mode) DPRINTF("\tClient connecting\n");
383
384         rv = PR_Connect(clientSocket, 
385                         &serverAddr,
386                         PR_INTERVAL_NO_TIMEOUT);
387         if (!clientSocket) {
388             if (debug_mode) printf("\tClient error connecting\n");
389             continue;
390         }
391
392         if (debug_mode) DPRINTF("\tClient connected\n");
393
394         rv = PR_Send(clientSocket, 
395                      sendBuf, 
396                      _client_data, 
397                      0, 
398                      PR_INTERVAL_NO_TIMEOUT);
399         if (rv != _client_data) {
400             if (debug_mode) printf("Client error sending data (%d)\n", rv);
401             PR_Close(clientSocket);
402             continue;
403         }
404
405         if (debug_mode) DPRINTF("\tClient sent %d bytes\n", rv);
406
407         bytesNeeded = _server_data;
408         while(bytesNeeded) {
409             rv = PR_Recv(clientSocket, 
410                          recvBuf, 
411                          bytesNeeded, 
412                          0, 
413                          PR_INTERVAL_NO_TIMEOUT);
414             if (rv <= 0) {
415                 if (debug_mode) printf("Client error receiving data (%d) (%d/%d)\n", 
416                     rv, (_server_data - bytesNeeded), _server_data);
417                 break;
418             }
419             if (debug_mode) DPRINTF("\tClient received %d bytes; need %d more\n", rv, bytesNeeded - rv);
420             bytesNeeded -= rv;
421         }
422
423         PR_Close(clientSocket);
424  
425         PR_AtomicDecrement(&numRequests);
426     }
427
428     PR_EnterMonitor(clientMonitor);
429     --numClients;
430     PR_Notify(clientMonitor);
431     PR_ExitMonitor(clientMonitor);
432
433     PR_DELETE(sendBuf);
434     PR_DELETE(recvBuf);
435 }
436
437 void
438 RunClients(void)
439 {
440     PRInt32 index;
441
442     numRequests = _iterations;
443     numClients = _clients;
444     clientMonitor = PR_NewMonitor();
445
446     for (index=0; index<_clients; index++) {
447         PRThread *clientThread;
448
449   
450         clientThread = PR_CreateThread(
451                           PR_USER_THREAD,
452                           ClientThreadFunc,
453                           NULL,
454                           PR_PRIORITY_NORMAL,
455                           ClientScope,
456                           PR_UNJOINABLE_THREAD,
457                           THREAD_STACKSIZE);
458
459         if (!clientThread) {
460             if (debug_mode) printf("\terror creating client thread %d\n", index);
461         } else
462             if (debug_mode) DPRINTF("\tMain created client %d/%d\n", index+1, _clients);
463
464     }
465
466     PR_EnterMonitor(clientMonitor);
467     while(numClients)
468         PR_Wait(clientMonitor, PR_INTERVAL_NO_TIMEOUT);
469     PR_ExitMonitor(clientMonitor);
470 }
471
472 /* --- Main Function ---------------------------------------------- */
473
474 static
475 void do_work()
476 {
477     PRThread *ServerThread;
478     PRInt32 state;
479
480     SetServerState(MAIN, SERVER_STATE_STARTUP);
481     ServerThread = PR_CreateThread(
482                       PR_USER_THREAD,
483                       ServerThreadFunc,
484                       NULL,
485                       PR_PRIORITY_NORMAL,
486                       ServerScope,
487                       PR_JOINABLE_THREAD,
488                       THREAD_STACKSIZE);
489     if (!ServerThread) {
490         if (debug_mode) printf("error creating main server thread\n");
491         return;
492     }
493
494     /* Wait for server to be ready */
495     state = WaitServerState(MAIN, SERVER_STATE_READY|SERVER_STATE_DEAD);
496
497     if (!(state & SERVER_STATE_DEAD)) {
498         /* Run Test Clients */
499         RunClients();
500
501         /* Send death signal to server */
502         SetServerState(MAIN, SERVER_STATE_DYING);
503     }
504
505     PR_JoinThread(ServerThread);
506 }
507
508
509 static void do_workKU(void)
510 {
511     ServerScope = PR_GLOBAL_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_workKU, "server loop kernel/user");
593
594     PR_Cleanup();
595         if(failed_already)      
596                 return 1;
597         else
598                 return 0;
599
600 }