stream performance - implemented 1 hop throughput calculation
[oweals/gnunet.git] / src / stream / perf_stream_api.c
1 /*
2      This file is part of GNUnet.
3      (C) 2011, 2012 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file stream/perf_stream_api.c
23  * @brief performance benchmarks for stream api
24  * @author Sree Harsha Totakura
25  */
26
27 #define LOG(kind, ...)                         \
28   GNUNET_log (kind, __VA_ARGS__);
29
30 /****************************************************************************************/
31 /* Test is setup into the following major steps:                                        */
32 /*    1. Measurements over loopback (1 hop). i.e. we use only one peer and open         */
33 /*       stream connections over loopback. Messages will go through                     */
34 /*       STREAM_API->MESH_API->MESH_SERVICE->MESH_API->STREAM_API.                      */
35 /*    2. Measurements over 2 peers (2 hops). We use testbed to create 2 peers,          */
36 /*       connect them and then create stream connections. Messages will go through      */
37 /*       STREAM_API->MESH_API->MESH_SERVICE->CORE1.....CORE2->MESH_API->STREAM_API      */
38 /*    3. Measurements over 3 peers (3 hops). We use testbed to create 3 peers,          */
39 /*       connect them in a line topology: peer1->peer2->peer3. Messages will go         */
40 /*       through                                                                        */
41 /*       STREAM_API->MESH_API->MESH_SERVICE->CORE1..CORE2..CORE3->MESH_API->STREAM_API. */
42 /****************************************************************************************/
43
44 #include "platform.h"
45 #include "gnunet_common.h"
46 #include "gnunet_util_lib.h"
47 #include "gnunet_testing_lib.h"
48 #include "gnunet_testbed_service.h"
49 #include "gnunet_stream_lib.h"
50
51
52   
53 /**
54  * Simple struct to keep track of progress, and print a
55  * nice little percentage meter for long running tasks.
56  */
57 struct ProgressMeter
58 {
59   unsigned int total;
60
61   unsigned int modnum;
62
63   unsigned int dotnum;
64
65   unsigned int completed;
66
67   int print;
68
69   char *startup_string;
70 };
71
72
73 /**
74  * Steps in testing
75  */
76 enum TestStep
77 {
78   /**
79    * Single hop loopback testing
80    */
81   TEST_STEP_1_HOP,
82
83   /**
84    * Testing with 2 peers
85    */
86   TEST_STEP_2_HOP,
87
88   /**
89    * Testing with 3 peers
90    */
91   TEST_STEP_3_HOP
92 };
93
94
95 /**
96  * Structure for holding peer's sockets and IO Handles
97  */
98 struct PeerData
99 {
100   /**
101    * Peer's stream socket
102    */
103   struct GNUNET_STREAM_Socket *socket;
104
105   struct GNUNET_PeerIdentity self;
106
107   /**
108    * Peer's io write handle
109    */
110   struct GNUNET_STREAM_IOWriteHandle *io_write_handle;
111
112   /**
113    * Peer's io read handle
114    */
115   struct GNUNET_STREAM_IOReadHandle *io_read_handle;
116
117   /**
118    * Bytes the peer has written
119    */
120   unsigned int bytes_wrote;
121
122   /**
123    * Byte the peer has read
124    */
125   unsigned int bytes_read;
126 };
127
128
129 /**
130  * Maximum size of the data which we will transfer during tests
131  */
132 #define DATA_SIZE 65536      /* 64KB */
133
134 /**
135  * Listen socket of peer2
136  */
137 struct GNUNET_STREAM_ListenSocket *peer2_listen_socket;
138
139 /**
140  * Handle to configuration during TEST_STEP_1_HOP
141  */
142 const struct GNUNET_CONFIGURATION_Handle *config;
143
144 /**
145  * Handle for the progress meter
146  */
147 static struct ProgressMeter *meter;
148
149 /**
150  * Placeholder for peer data
151  */
152 static struct PeerData peer_data[3];
153
154 /**
155  * Task ID for abort task
156  */
157 static GNUNET_SCHEDULER_TaskIdentifier abort_task;
158
159 /**
160  * Task ID for write task
161  */
162 static GNUNET_SCHEDULER_TaskIdentifier write_task;
163
164 /**
165  * Task ID for read task
166  */
167 static GNUNET_SCHEDULER_TaskIdentifier read_task;
168
169 /**
170  * Absolute time when profiling starts
171  */
172 static struct GNUNET_TIME_Absolute prof_start_time;
173
174 /**
175  * Test time taken for sending the data
176  */
177 static struct GNUNET_TIME_Relative prof_time;
178
179 /**
180  * Random data block. Should generate data first
181  */
182 static uint32_t data[DATA_SIZE / 4];     /* 64KB array */
183
184 /**
185  * Payload sizes to test each major test with
186  */
187 static uint16_t payload_size[] = 
188 { 20, 500, 2000, 7000, 13000, 25000, 56000, 64000 };
189
190 /**
191  * Handle for the progress meter
192  */
193 static struct ProgressMeter *meter;
194
195 /**
196  * Current step of testing
197  */
198 static enum TestStep test_step;
199
200 /**
201  * Index for choosing payload size
202  */
203 static unsigned int payload_size_index;
204
205 /**
206  * Testing result of a major test
207  */
208 static int result;
209
210 /**
211  * Create a meter to keep track of the progress of some task.
212  *
213  * @param total the total number of items to complete
214  * @param start_string a string to prefix the meter with (if printing)
215  * @param print GNUNET_YES to print the meter, GNUNET_NO to count
216  *              internally only
217  *
218  * @return the progress meter
219  */
220 static struct ProgressMeter *
221 create_meter (unsigned int total, char *start_string, int print)
222 {
223   struct ProgressMeter *ret;
224
225   ret = GNUNET_malloc (sizeof (struct ProgressMeter));
226   ret->print = print;
227   ret->total = total;
228   ret->modnum = total / 4;
229   if (ret->modnum == 0)         /* Divide by zero check */
230     ret->modnum = 1;
231   ret->dotnum = (total / 50) + 1;
232   if (start_string != NULL)
233     ret->startup_string = GNUNET_strdup (start_string);
234   else
235     ret->startup_string = GNUNET_strdup ("");
236
237   return ret;
238 }
239
240
241 /**
242  * Update progress meter (increment by one).
243  *
244  * @param meter the meter to update and print info for
245  *
246  * @return GNUNET_YES if called the total requested,
247  *         GNUNET_NO if more items expected
248  */
249 static int
250 update_meter (struct ProgressMeter *meter)
251 {
252   if (meter->print == GNUNET_YES)
253   {
254     if (meter->completed % meter->modnum == 0)
255     {
256       if (meter->completed == 0)
257       {
258         FPRINTF (stdout, "%sProgress: [0%%", meter->startup_string);
259       }
260       else
261         FPRINTF (stdout, "%d%%",
262                  (int) (((float) meter->completed / meter->total) * 100));
263     }
264     else if (meter->completed % meter->dotnum == 0)
265       FPRINTF (stdout, "%s",  ".");
266
267     if (meter->completed + 1 == meter->total)
268       FPRINTF (stdout, "%d%%]\n", 100);
269     fflush (stdout);
270   }
271   meter->completed++;
272
273   if (meter->completed == meter->total)
274     return GNUNET_YES;
275   if (meter->completed > meter->total)
276     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Progress meter overflow!!\n");
277   return GNUNET_NO;
278 }
279
280
281 /**
282  * Reset progress meter.
283  *
284  * @param meter the meter to reset
285  *
286  * @return GNUNET_YES if meter reset,
287  *         GNUNET_SYSERR on error
288  */
289 static int
290 reset_meter (struct ProgressMeter *meter)
291 {
292   if (meter == NULL)
293     return GNUNET_SYSERR;
294
295   meter->completed = 0;
296   return GNUNET_YES;
297 }
298
299
300 /**
301  * Release resources for meter
302  *
303  * @param meter the meter to free
304  */
305 static void
306 free_meter (struct ProgressMeter *meter)
307 {
308   GNUNET_free_non_null (meter->startup_string);
309   GNUNET_free (meter);
310 }
311
312
313 /**
314  * Shutdown nicely
315  */
316 static void
317 do_shutdown (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
318 {
319   GNUNET_STREAM_close (peer_data[1].socket);
320   if (NULL != peer_data[2].socket)
321     GNUNET_STREAM_close (peer_data[2].socket);
322   if (NULL != peer2_listen_socket)
323     GNUNET_STREAM_listen_close (peer2_listen_socket); /* Close listen socket */
324   if (GNUNET_SCHEDULER_NO_TASK != abort_task)
325     GNUNET_SCHEDULER_cancel (abort_task);
326   if (GNUNET_SCHEDULER_NO_TASK != write_task)
327     GNUNET_SCHEDULER_cancel (write_task);
328   GNUNET_SCHEDULER_shutdown (); /* Shutdown this testcase */
329 }
330
331
332 /**
333  * Something went wrong and timed out. Kill everything and set error flag
334  */
335 static void
336 do_abort (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
337 {
338   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "test: ABORT\n");
339   if (GNUNET_SCHEDULER_NO_TASK != read_task)
340     GNUNET_SCHEDULER_cancel (read_task);
341   result = GNUNET_SYSERR;
342   abort_task = GNUNET_SCHEDULER_NO_TASK;
343   do_shutdown (cls, tc);
344 }
345
346
347 /**
348  * The write completion function; called upon writing some data to stream or
349  * upon error
350  *
351  * @param cls the closure from GNUNET_STREAM_write/read
352  * @param status the status of the stream at the time this function is called
353  * @param size the number of bytes read or written
354  */
355 static void 
356 write_completion (void *cls, enum GNUNET_STREAM_Status status, size_t size)
357 {
358   struct PeerData *pdata = cls;
359
360   GNUNET_assert (GNUNET_STREAM_OK == status);
361   GNUNET_assert (size <= DATA_SIZE);
362   pdata->bytes_wrote += size;  
363   if (pdata->bytes_wrote < DATA_SIZE) /* Have more data to send */
364   {
365     pdata->io_write_handle =
366         GNUNET_STREAM_write (pdata->socket,
367                              ((void *) data) + pdata->bytes_wrote,
368                              sizeof (data) - pdata->bytes_wrote,
369                              GNUNET_TIME_UNIT_FOREVER_REL, &write_completion,
370                              pdata);
371     GNUNET_assert (NULL != pdata->io_write_handle);
372   }
373   else
374   {
375     prof_time = GNUNET_TIME_absolute_get_duration (prof_start_time);
376     result = GNUNET_OK;
377     GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
378   }
379   for (;size > 0; size--)
380     update_meter (meter);
381 }
382
383
384 /**
385  * Task for calling STREAM_write with a chunk of random data
386  *
387  * @param cls the peer data entity
388  * @param tc the task context
389  */
390 static void
391 stream_write_task (void *cls,
392                    const struct GNUNET_SCHEDULER_TaskContext *tc)
393 {
394   struct PeerData *pdata = cls;
395   
396   write_task = GNUNET_SCHEDULER_NO_TASK;
397   prof_start_time = GNUNET_TIME_absolute_get ();
398   pdata->bytes_wrote = 0;
399   pdata->io_write_handle = GNUNET_STREAM_write (pdata->socket, data,
400                                                 sizeof (data),
401                                                 GNUNET_TIME_UNIT_FOREVER_REL,
402                                                 &write_completion, pdata);
403   GNUNET_assert (NULL != pdata->io_write_handle);
404 }
405
406
407 /**
408  * Scheduler call back; to be executed when a new stream is connected
409  * Called from listen connect for peer2
410  */
411 static void
412 stream_read_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
413
414
415 /**
416  * Input processor
417  *
418  * @param cls peer2
419  * @param status the status of the stream at the time this function is called
420  * @param data traffic from the other side
421  * @param size the number of bytes available in data read 
422  * @return number of bytes of processed from 'data' (any data remaining should be
423  *         given to the next time the read processor is called).
424  */
425 static size_t
426 input_processor (void *cls, enum GNUNET_STREAM_Status status,
427                  const void *input_data, size_t size)
428 {
429   struct PeerData *pdata = cls;
430
431   GNUNET_assert (GNUNET_STREAM_OK == status);
432   GNUNET_assert (size < DATA_SIZE);
433   GNUNET_assert (0 == memcmp (((void *)data ) + pdata->bytes_read, 
434                               input_data, size));
435   pdata->bytes_read += size;
436   
437   if (pdata->bytes_read < DATA_SIZE)
438   {
439     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == read_task);
440     read_task = GNUNET_SCHEDULER_add_now (&stream_read_task, pdata);
441   }
442   else 
443   {
444     /* Peer2 has completed reading*/
445     LOG (GNUNET_ERROR_TYPE_DEBUG, "Reading finished successfully\n");
446   }
447   return size;
448 }
449
450   
451 /**
452  * Scheduler call back; to be executed when a new stream is connected
453  * Called from listen connect for peer2
454  */
455 static void
456 stream_read_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
457 {
458   struct PeerData *pdata = cls;
459
460   read_task = GNUNET_SCHEDULER_NO_TASK;
461   pdata->io_read_handle =
462       GNUNET_STREAM_read (pdata->socket, GNUNET_TIME_UNIT_FOREVER_REL,
463                           &input_processor, pdata);
464   GNUNET_assert (NULL != pdata->io_read_handle);
465 }
466
467
468 /**
469  * Functions of this type are called upon new stream connection from other peers
470  *
471  * @param cls the closure from GNUNET_STREAM_listen
472  * @param socket the socket representing the stream
473  * @param initiator the identity of the peer who wants to establish a stream
474  *            with us
475  * @return GNUNET_OK to keep the socket open, GNUNET_SYSERR to close the
476  *             stream (the socket will be invalid after the call)
477  */
478 static int
479 stream_listen_cb (void *cls, struct GNUNET_STREAM_Socket *socket,
480                   const struct GNUNET_PeerIdentity *initiator)
481 {
482   struct PeerData *pdata = cls;
483
484   GNUNET_assert (NULL != socket);
485   GNUNET_assert (pdata == &peer_data[2]);
486   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Peer connected: %s\n", 
487               GNUNET_i2s(initiator));
488   pdata->socket = socket;
489   pdata->bytes_read = 0;
490   read_task = GNUNET_SCHEDULER_add_now (&stream_read_task, pdata);
491   return GNUNET_OK;
492 }
493
494
495 /**
496  * Function executed after stream has been established
497  *
498  * @param cls the closure from GNUNET_STREAM_open
499  * @param socket socket to use to communicate with the other side (read/write)
500  */
501 static void 
502 stream_open_cb (void *cls,
503                 struct GNUNET_STREAM_Socket *socket)
504 {
505   struct PeerData *pdata = cls;
506
507   GNUNET_assert (socket == pdata->socket);
508   write_task = GNUNET_SCHEDULER_add_now (&stream_write_task, pdata);
509 }
510
511
512 /**
513  * Listen success callback; connects a peer to stream as client
514  */
515 static void
516 stream_connect (void)
517 {
518   peer_data[1].socket = 
519       GNUNET_STREAM_open (config, &peer_data[2].self, 10, &stream_open_cb,
520                           &peer_data[1],
521                           GNUNET_STREAM_OPTION_MAX_PAYLOAD_SIZE, 500,
522                           GNUNET_STREAM_OPTION_END);
523   GNUNET_assert (NULL != peer_data[1].socket);
524 }
525
526
527 /**
528  * Initialize framework and start test
529  *
530  * @param cls closure
531  * @param cfg configuration of the peer that was started
532  * @param peer identity of the peer that was created
533  */
534 static void
535 run (void *cls, 
536      const struct GNUNET_CONFIGURATION_Handle *cfg,
537      struct GNUNET_TESTING_Peer *peer)
538 {
539   struct GNUNET_PeerIdentity self;
540
541   GNUNET_TESTING_peer_get_identity (peer, &self);
542   config = cfg;
543   peer2_listen_socket = 
544       GNUNET_STREAM_listen (config, 10, &stream_listen_cb, &peer_data[2],
545                             GNUNET_STREAM_OPTION_SIGNAL_LISTEN_SUCCESS,
546                             &stream_connect, GNUNET_STREAM_OPTION_END);
547   GNUNET_assert (NULL != peer2_listen_socket);
548   peer_data[1].self = self;
549   peer_data[2].self = self;
550   abort_task =
551     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
552                                   (GNUNET_TIME_UNIT_SECONDS, 60), &do_abort,
553                                   NULL);
554 }
555
556
557 /**
558  * Main function
559  */
560 int main (int argc, char **argv)
561 {
562   char *pmsg;
563   char *test_name = "perf_stream_api";
564   char *cfg_file = "test_stream_local.conf";
565   double throughput;
566   double prof_time_sec;
567   unsigned int count;
568   int ret;
569
570   meter = create_meter ((sizeof (data) / 4), "Generating random data\n", GNUNET_YES);
571   for (count=0; count < (sizeof (data) / 4); count++)
572   {
573     data[count] = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
574                                             UINT32_MAX);
575     update_meter (meter);
576   }
577   reset_meter (meter);
578   free_meter (meter);
579   test_step = TEST_STEP_1_HOP;
580   for (payload_size_index = 0; 
581        payload_size_index < (sizeof (payload_size) / sizeof (uint16_t));
582        payload_size_index++)
583   {
584     GNUNET_asprintf (&pmsg, "\nTesting over loopback with payload size %hu\n",
585                      payload_size[payload_size_index]);
586     meter = create_meter (sizeof (data), pmsg, GNUNET_YES);
587     GNUNET_free (pmsg);
588     result = GNUNET_SYSERR;
589     ret = GNUNET_TESTING_peer_run (test_name, cfg_file, &run, NULL);
590     free_meter (meter);
591     if ((0 != ret) || (GNUNET_OK != result))
592       goto return_fail;
593     prof_time_sec = (((double) prof_time.rel_value)/ ((double) 1000));
594     throughput = (((float) sizeof (data)) / prof_time_sec);
595     //PRINTF ("Profiling time %llu ms = %.2f sec\n", prof_time.rel_value, prof_time_sec);
596     PRINTF ("Throughput %.2f kB/sec\n", throughput / 1000.00);
597   }
598   test_step = TEST_STEP_2_HOP;
599   for (payload_size_index = 0; 
600        payload_size_index < (sizeof (payload_size) / sizeof (uint16_t));
601        payload_size_index++)
602   {
603     /* Initialize testbed here */
604   }
605   test_step = TEST_STEP_3_HOP;
606   for (payload_size_index = 0; 
607        payload_size_index < (sizeof (payload_size) / sizeof (uint16_t));
608        payload_size_index++)
609   {
610     /* Initialize testbed here */
611   }
612   return ret;
613
614  return_fail:
615   GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Test failed\n");
616   return 1;
617 }