- add stddev
[oweals/gnunet.git] / src / mesh / gnunet-mesh-profiler.c
1 /*
2      This file is part of GNUnet.
3      (C) 2011 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  * @file mesh/gnunet-mesh-profiler.c
22  *
23  * @brief Profiler for mesh experiments.
24  */
25 #include <stdio.h>
26 #include "platform.h"
27 #include "mesh_test_lib.h"
28 #include "gnunet_mesh_service.h"
29 #include "gnunet_statistics_service.h"
30
31
32 #define PING 1
33 #define PONG 2
34
35 /**
36  * How many peers to run
37  */
38 #define TOTAL_PEERS 20
39
40 /**
41  * How many peers do pinging
42  */
43 #define PING_PEERS 3
44
45 /**
46  * Duration of each round.
47  */
48 #define ROUND_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
49
50 /**
51  * Paximum ping period in milliseconds. Real period = rand (0, PING_PERIOD)
52  */
53 #define PING_PERIOD 1000
54
55 /**
56  * How long until we give up on connecting the peers?
57  */
58 #define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 120)
59
60 /**
61  * Time to wait for stuff that should be rather fast
62  */
63 #define SHORT_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60)
64
65 /**
66  * Total number of rounds.
67  */
68 #define number_rounds sizeof(rounds)/sizeof(rounds[0])
69
70 /**
71  * Ratio of peers active. First round always is 1.0.
72  */
73 static float rounds[] = {0.8, 0.7, 0.6, 0.5, 0.0};
74
75 /**
76  * Message type for pings.
77  */
78 struct MeshPingMessage
79 {
80   /**
81    * Header. Type PING/PONG.
82    */
83   struct GNUNET_MessageHeader header;
84
85   /**
86    * Message number.
87    */
88   uint32_t counter;
89
90   /**
91    * Time the message was sent.
92    */
93   struct GNUNET_TIME_AbsoluteNBO timestamp;
94
95   /**
96    * Round number.
97    */
98   uint32_t round_number;
99 };
100
101 /**
102  * Peer description.
103  */
104 struct MeshPeer
105 {
106   /**
107    * Testbed Operation (to get peer id, etc).
108    */
109   struct GNUNET_TESTBED_Operation *op;
110
111   /**
112    * Peer ID.
113    */
114   struct GNUNET_PeerIdentity id;
115
116   /**
117    * Mesh handle for the root peer
118    */
119   struct GNUNET_MESH_Handle *mesh;
120
121   /**
122    * Channel handle for the root peer
123    */
124   struct GNUNET_MESH_Channel *ch;
125
126   /**
127    * Channel handle for the dest peer
128    */
129   struct GNUNET_MESH_Channel *incoming_ch;
130
131   /**
132    * Number of payload packes sent
133    */
134   int data_sent;
135
136   /**
137    * Number of payload packets received
138    */
139   int data_received;
140
141   /**
142    * Is peer up?
143    */
144   int up;
145
146   /**
147    * Destinaton to ping.
148    */
149   struct MeshPeer *dest;
150
151   /**
152    * Incoming channel for pings.
153    */
154   struct MeshPeer *incoming;
155
156   /**
157    * Task to do the next ping.
158    */
159   GNUNET_SCHEDULER_TaskIdentifier ping_task;
160
161   float mean[number_rounds];
162   float var[number_rounds];
163   unsigned int pongs[number_rounds];
164   unsigned int pings[number_rounds];
165
166 };
167
168 /**
169  * GNUNET_PeerIdentity -> MeshPeer
170  */
171 static struct GNUNET_CONTAINER_MultiPeerMap *ids;
172
173 /**
174  * Testbed peer handles.
175  */
176 static struct GNUNET_TESTBED_Peer **testbed_handles;
177
178 /**
179  * Testbed Operation (to get stats).
180  */
181 static struct GNUNET_TESTBED_Operation *stats_op;
182
183 /**
184  * Operation to get peer ids.
185  */
186 struct MeshPeer peers[TOTAL_PEERS];
187
188 /**
189  * Peer ids counter.
190  */
191 static unsigned int p_ids;
192
193 /**
194  * Total number of currently running peers.
195  */
196 static unsigned long long peers_running;
197
198 /**
199  * Test context (to shut down).
200  */
201 static struct GNUNET_MESH_TEST_Context *test_ctx;
202
203 /**
204  * Task called to shutdown test.
205  */
206 static GNUNET_SCHEDULER_TaskIdentifier shutdown_handle;
207
208 /**
209  * Task called to disconnect peers, before shutdown.
210  */
211 static GNUNET_SCHEDULER_TaskIdentifier disconnect_task;
212
213 /**
214  * Task to perform tests
215  */
216 static GNUNET_SCHEDULER_TaskIdentifier test_task;
217
218 /**
219  * Round number.
220  */
221 static unsigned int current_round;
222
223 /**
224  * Flag to notify callbacks not to generate any new traffic anymore.
225  */
226 static int test_finished;
227
228 /**
229  * Calculate a random delay.
230  *
231  * @param max Exclusive maximum, in ms.
232  *
233  * @return A time between 0 a max-1 ms.
234  */
235 static struct GNUNET_TIME_Relative
236 delay_ms_rnd (unsigned int max)
237 {
238   unsigned int rnd;
239
240   rnd = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, max);
241   return GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, rnd);
242 }
243
244
245 /**
246  * Get the index of a peer in the peers array.
247  *
248  * @param peer Peer whose index to get.
249  *
250  * @return Index of peer in peers.
251  */
252 static unsigned int
253 get_index (struct MeshPeer *peer)
254 {
255   return peer - peers;
256 }
257
258
259 /**
260  * Show the results of the test (banwidth acheived) and log them to GAUGER
261  */
262 static void
263 show_end_data (void)
264 {
265   struct MeshPeer *peer;
266   unsigned int i;
267   unsigned int j;
268
269   for (i = 0; i < number_rounds; i++)
270   {
271     for (j = 0; j < PING_PEERS; j++)
272     {
273       peer = &peers[j];
274       FPRINTF (stdout,
275                "ROUND %3u PEER %3u: %10.2f / %10.2f, PINGS: %3u, PONGS: %3u\n",
276                i, j, peer->mean[i], sqrt (peer->var[i] / (peer->pongs[i] - 1)),
277                peer->pings[i], peer->pongs[i]);
278     }
279   }
280 }
281
282
283 /**
284  * Shut down peergroup, clean up.
285  *
286  * @param cls Closure (unused).
287  * @param tc Task Context.
288  */
289 static void
290 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
291 {
292   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Ending test.\n");
293   shutdown_handle = GNUNET_SCHEDULER_NO_TASK;
294 }
295
296
297 /**
298  * Disconnect from mesh services af all peers, call shutdown.
299  *
300  * @param cls Closure (unused).
301  * @param tc Task Context.
302  */
303 static void
304 disconnect_mesh_peers (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
305 {
306   long line = (long) cls;
307   unsigned int i;
308
309   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
310               "disconnecting mesh service, called from line %ld\n", line);
311   disconnect_task = GNUNET_SCHEDULER_NO_TASK;
312   for (i = 0; i < TOTAL_PEERS; i++)
313   {
314     if (NULL != peers[i].op)
315       GNUNET_TESTBED_operation_done (peers[i].op);
316
317     if (peers[i].up != GNUNET_YES)
318       continue;
319
320     if (NULL != peers[i].ch)
321     {
322       GNUNET_log (GNUNET_ERROR_TYPE_INFO, "%u: channel %p\n", i, peers[i].ch);
323       GNUNET_MESH_channel_destroy (peers[i].ch);
324     }
325     if (NULL != peers[i].incoming_ch)
326     {
327       GNUNET_log (GNUNET_ERROR_TYPE_INFO, "%u: incoming channel %p\n",
328                   i, peers[i].incoming_ch);
329       GNUNET_MESH_channel_destroy (peers[i].incoming_ch);
330     }
331   }
332   GNUNET_MESH_TEST_cleanup (test_ctx);
333   if (GNUNET_SCHEDULER_NO_TASK != shutdown_handle)
334   {
335     GNUNET_SCHEDULER_cancel (shutdown_handle);
336   }
337   shutdown_handle = GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
338 }
339
340
341 /**
342  * Finish test normally: schedule disconnect and shutdown
343  *
344  * @param line Line in the code the abort is requested from (__LINE__).
345  */
346 static void
347 abort_test (long line)
348 {
349   if (disconnect_task != GNUNET_SCHEDULER_NO_TASK)
350   {
351     GNUNET_SCHEDULER_cancel (disconnect_task);
352     disconnect_task = GNUNET_SCHEDULER_add_now (&disconnect_mesh_peers,
353                                                 (void *) line);
354   }
355 }
356
357 /**
358  * Stats callback. Finish the stats testbed operation and when all stats have
359  * been iterated, shutdown the test.
360  *
361  * @param cls closure
362  * @param op the operation that has been finished
363  * @param emsg error message in case the operation has failed; will be NULL if
364  *          operation has executed successfully.
365  */
366 static void
367 stats_cont (void *cls, struct GNUNET_TESTBED_Operation *op, const char *emsg)
368 {
369   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "... collecting statistics done.\n");
370   GNUNET_TESTBED_operation_done (stats_op);
371
372   if (GNUNET_SCHEDULER_NO_TASK != disconnect_task)
373     GNUNET_SCHEDULER_cancel (disconnect_task);
374   disconnect_task = GNUNET_SCHEDULER_add_now (&disconnect_mesh_peers,
375                                               (void *) __LINE__);
376
377 }
378
379
380 /**
381  * Process statistic values.
382  *
383  * @param cls closure
384  * @param peer the peer the statistic belong to
385  * @param subsystem name of subsystem that created the statistic
386  * @param name the name of the datum
387  * @param value the current value
388  * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
389  * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
390  */
391 static int
392 stats_iterator (void *cls, const struct GNUNET_TESTBED_Peer *peer,
393                 const char *subsystem, const char *name,
394                 uint64_t value, int is_persistent)
395 {
396   uint32_t i;
397
398   i = GNUNET_TESTBED_get_index (peer);
399   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " STATS %u - %s [%s]: %llu\n",
400               i, subsystem, name, value);
401
402   return GNUNET_OK;
403 }
404
405
406 /**
407  * Task check that keepalives were sent and received.
408  *
409  * @param cls Closure (NULL).
410  * @param tc Task Context.
411  */
412 static void
413 collect_stats (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
414 {
415   if ((GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason) != 0)
416     return;
417
418   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Start collecting statistics...\n");
419   stats_op = GNUNET_TESTBED_get_statistics (TOTAL_PEERS, testbed_handles,
420                                             NULL, NULL,
421                                             stats_iterator, stats_cont, NULL);
422 }
423
424
425 /**
426  * @brief Finish profiler normally. Signal finish and start collecting stats.
427  *
428  * @param cls Closure (unused).
429  * @param tc Task context.
430  */
431 static void
432 finish_profiler (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
433 {
434   if ((GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason) != 0)
435     return;
436
437   test_finished = GNUNET_YES;
438   show_end_data();
439   GNUNET_SCHEDULER_add_now (&collect_stats, NULL);
440 }
441
442 /**
443  * Set the total number of running peers.
444  *
445  * @param target Desired number of running peers.
446  */
447 static void
448 adjust_running_peers (unsigned int target)
449 {
450   struct GNUNET_TESTBED_Operation *op;
451   unsigned int delta;
452   unsigned int run;
453   unsigned int i;
454   unsigned int r;
455
456   GNUNET_assert (target <= TOTAL_PEERS);
457
458   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "adjust peers to %u\n", target);
459   if (target > peers_running)
460   {
461     delta = target - peers_running;
462     run = GNUNET_YES;
463   }
464   else
465   {
466     delta = peers_running - target;
467     run = GNUNET_NO;
468   }
469
470   for (i = 0; i < delta; i++)
471   {
472     do {
473       r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
474                                     TOTAL_PEERS - PING_PEERS);
475       r += PING_PEERS;
476     } while (peers[r].up == run || NULL != peers[r].incoming);
477     GNUNET_log (GNUNET_ERROR_TYPE_INFO, "St%s peer %u: %s\n",
478                 run ? "arting" : "opping", r, GNUNET_i2s (&peers[r].id));
479
480     if (GNUNET_SCHEDULER_NO_TASK != peers[r].ping_task)
481       GNUNET_SCHEDULER_cancel (peers[r].ping_task);
482     peers[r].ping_task = GNUNET_SCHEDULER_NO_TASK;
483
484     peers[r].up = run;
485
486     if (NULL != peers[r].ch)
487       GNUNET_MESH_channel_destroy (peers[r].ch);
488     peers[r].ch = NULL;
489     if (NULL != peers[r].dest)
490     {
491       if (NULL != peers[r].dest->incoming_ch)
492         GNUNET_MESH_channel_destroy (peers[r].dest->incoming_ch);
493       peers[r].dest->incoming_ch = NULL;
494     }
495
496     op = GNUNET_TESTBED_peer_manage_service (&peers[r], testbed_handles[r],
497                                              "mesh", NULL, NULL, run);
498     GNUNET_break (NULL != op);
499     peers_running += run ? 1 : -1;
500     GNUNET_assert (peers_running > 0);
501   }
502 }
503
504
505 /**
506  * @brief Move to next round.
507  *
508  * @param cls Closure (round #).
509  * @param tc Task context.
510  */
511 static void
512 next_rnd (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
513 {
514   if ((GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason) != 0)
515     return;
516
517   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "ROUND %ld\n", current_round);
518   if (0.0 == rounds[current_round])
519   {
520     GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Finishing\n");
521     GNUNET_SCHEDULER_add_now (&finish_profiler, NULL);
522     return;
523   }
524   adjust_running_peers (rounds[current_round] * TOTAL_PEERS);
525   current_round++;
526
527   GNUNET_SCHEDULER_add_delayed (ROUND_TIME, &next_rnd, NULL);
528 }
529
530
531 /**
532  * Transmit ping callback.
533  *
534  * @param cls Closure (peer for PING, NULL for PONG).
535  * @param size Size of the tranmist buffer.
536  * @param buf Pointer to the beginning of the buffer.
537  *
538  * @return Number of bytes written to buf.
539  */
540 static size_t
541 tmt_rdy_ping (void *cls, size_t size, void *buf);
542
543
544 /**
545  * Transmit pong callback.
546  *
547  * @param cls Closure (copy of PING message, to be freed).
548  * @param size Size of the buffer we have.
549  * @param buf Buffer to copy data to.
550  */
551 static size_t
552 tmt_rdy_pong (void *cls, size_t size, void *buf)
553 {
554   struct MeshPingMessage *ping = cls;
555   struct MeshPingMessage *pong;
556
557   if (0 == size || NULL == buf)
558   {
559     GNUNET_free (ping);
560     return 0;
561   }
562   pong = (struct MeshPingMessage *) buf;
563   memcpy (pong, ping, sizeof (*ping));
564   pong->header.type = htons (PONG);
565
566   GNUNET_free (ping);
567   return sizeof (*ping);
568 }
569
570
571 /**
572  * @brief Send a ping to destination
573  *
574  * @param cls Closure (peer).
575  * @param tc Task context.
576  */
577 static void
578 ping (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
579 {
580   struct MeshPeer *peer = (struct MeshPeer *) cls;
581
582   peer->ping_task = GNUNET_SCHEDULER_NO_TASK;
583
584   if ((GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason) != 0
585       || GNUNET_YES == test_finished)
586     return;
587
588   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "%u -> %u (%u)\n",
589               get_index (peer), get_index (peer->dest), peer->data_sent);
590
591   GNUNET_MESH_notify_transmit_ready (peer->ch, GNUNET_NO,
592                                      GNUNET_TIME_UNIT_FOREVER_REL,
593                                      sizeof (struct MeshPingMessage),
594                                      &tmt_rdy_ping, peer);
595 }
596
597 /**
598  * @brief Reply with a pong to origin.
599  *
600  * @param cls Closure (peer).
601  * @param tc Task context.
602  */
603 static void
604 pong (struct GNUNET_MESH_Channel *channel, const struct MeshPingMessage *ping)
605 {
606   struct MeshPingMessage *copy;
607
608   copy = GNUNET_new (struct MeshPingMessage);
609   memcpy (copy, ping, sizeof (*ping));
610   GNUNET_MESH_notify_transmit_ready (channel, GNUNET_NO,
611                                      GNUNET_TIME_UNIT_FOREVER_REL,
612                                      sizeof (struct MeshPingMessage),
613                                      &tmt_rdy_pong, copy);
614 }
615
616
617 /**
618  * Transmit ping callback
619  *
620  * @param cls Closure (peer).
621  * @param size Size of the buffer we have.
622  * @param buf Buffer to copy data to.
623  */
624 static size_t
625 tmt_rdy_ping (void *cls, size_t size, void *buf)
626 {
627   struct MeshPeer *peer = (struct MeshPeer *) cls;
628   struct MeshPingMessage *msg = buf;
629
630   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tmt_rdy called, filling buffer\n");
631   if (size < sizeof (struct MeshPingMessage) || NULL == buf)
632   {
633     GNUNET_break (0);
634     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
635                 "size %u, buf %p, data_sent %u, data_received %u\n",
636                 size, buf, peer->data_sent, peer->data_received);
637
638     return 0;
639   }
640   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending: msg %d\n", peer->data_sent);
641   msg->header.size = htons (size);
642   msg->header.type = htons (PING);
643   msg->counter = htonl (peer->data_sent++);
644   msg->round_number = htonl (current_round);
645   msg->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
646   peer->pings[current_round]++;
647   peer->ping_task = GNUNET_SCHEDULER_add_delayed (delay_ms_rnd (PING_PERIOD),
648                                                   &ping, peer);
649
650   return sizeof (struct MeshPingMessage);
651 }
652
653
654 /**
655  * Function is called whenever a PING message is received.
656  *
657  * @param cls closure (peer #, set from GNUNET_MESH_connect)
658  * @param channel connection to the other end
659  * @param channel_ctx place to store local state associated with the channel
660  * @param message the actual message
661  * @return GNUNET_OK to keep the connection open,
662  *         GNUNET_SYSERR to close it (signal serious error)
663  */
664 int
665 ping_handler (void *cls, struct GNUNET_MESH_Channel *channel,
666               void **channel_ctx,
667               const struct GNUNET_MessageHeader *message)
668 {
669   long n = (long) cls;
670
671   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%u got PING\n", n);
672   GNUNET_MESH_receive_done (channel);
673   if (GNUNET_NO == test_finished)
674     pong (channel, (struct MeshPingMessage *) message);
675
676   return GNUNET_OK;
677 }
678
679
680 /**
681  * Function is called whenever a PONG message is received.
682  *
683  * @param cls closure (peer #, set from GNUNET_MESH_connect)
684  * @param channel connection to the other end
685  * @param channel_ctx place to store local state associated with the channel
686  * @param message the actual message
687  * @return GNUNET_OK to keep the connection open,
688  *         GNUNET_SYSERR to close it (signal serious error)
689  */
690 int
691 pong_handler (void *cls, struct GNUNET_MESH_Channel *channel,
692               void **channel_ctx,
693               const struct GNUNET_MessageHeader *message)
694 {
695   long n = (long) cls;
696   struct MeshPeer *peer;
697   struct MeshPingMessage *msg;
698   struct GNUNET_TIME_Absolute send_time;
699   struct GNUNET_TIME_Relative latency;
700   unsigned int r /* Ping round */;
701   float delta;
702
703   GNUNET_MESH_receive_done (channel);
704   peer = &peers[n];
705
706   msg = (struct MeshPingMessage *) message;
707
708   send_time = GNUNET_TIME_absolute_ntoh (msg->timestamp);
709   latency = GNUNET_TIME_absolute_get_duration (send_time);
710   r = ntohl (msg->round_number);
711   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "%u <- %u (%u) latency: %s\n",
712               get_index (peer), get_index (peer->dest), ntohl (msg->counter),
713               GNUNET_STRINGS_relative_time_to_string (latency, GNUNET_NO));
714
715   /* Online variance calculation */
716   peer->pongs[r]++;
717   delta = latency.rel_value_us - peer->mean[r];
718   peer->mean[r] = peer->mean[r] + delta/peer->pongs[r];
719   peer->var[r] += delta * (latency.rel_value_us - peer->mean[r]);
720
721   return GNUNET_OK;
722 }
723
724
725 /**
726  * Handlers, for diverse services
727  */
728 static struct GNUNET_MESH_MessageHandler handlers[] = {
729   {&ping_handler, PING, sizeof (struct MeshPingMessage)},
730   {&pong_handler, PONG, sizeof (struct MeshPingMessage)},
731   {NULL, 0, 0}
732 };
733
734
735 /**
736  * Method called whenever another peer has added us to a channel
737  * the other peer initiated.
738  *
739  * @param cls Closure.
740  * @param channel New handle to the channel.
741  * @param initiator Peer that started the channel.
742  * @param port Port this channel is connected to.
743  * @param options channel option flags
744  * @return Initial channel context for the channel
745  *         (can be NULL -- that's not an error).
746  */
747 static void *
748 incoming_channel (void *cls, struct GNUNET_MESH_Channel *channel,
749                  const struct GNUNET_PeerIdentity *initiator,
750                  uint32_t port, enum GNUNET_MESH_ChannelOption options)
751 {
752   long n = (long) cls;
753   struct MeshPeer *peer;
754
755   peer = GNUNET_CONTAINER_multipeermap_get (ids, initiator);
756   GNUNET_assert (NULL != peer);
757   GNUNET_assert (peer == peers[n].incoming);
758   GNUNET_assert (peer->dest == &peers[n]);
759   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "%u <= %u %p\n",
760               n, get_index (peer), channel);
761   peers[n].incoming_ch = channel;
762
763   return NULL;
764 }
765
766 /**
767  * Function called whenever an inbound channel is destroyed.  Should clean up
768  * any associated state.
769  *
770  * @param cls closure (set from GNUNET_MESH_connect)
771  * @param channel connection to the other end (henceforth invalid)
772  * @param channel_ctx place where local state associated
773  *                   with the channel is stored
774  */
775 static void
776 channel_cleaner (void *cls, const struct GNUNET_MESH_Channel *channel,
777                  void *channel_ctx)
778 {
779   long n = (long) cls;
780   struct MeshPeer *peer = &peers[n];
781
782   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
783               "Channel %p disconnected at peer %ld\n", channel, n);
784   if (peer->ch == channel)
785     peer->ch = NULL;
786 }
787
788
789 static struct MeshPeer *
790 select_random_peer (struct MeshPeer *peer)
791 {
792   unsigned int r;
793
794   do
795   {
796     r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, TOTAL_PEERS);
797   } while (NULL != peers[r].incoming);
798   peers[r].incoming = peer;
799
800   return &peers[r];
801 }
802
803 /**
804  * START THE TEST ITSELF, AS WE ARE CONNECTED TO THE MESH SERVICES.
805  *
806  * Testcase continues when the root receives confirmation of connected peers,
807  * on callback funtion ch.
808  *
809  * @param cls Closure (unsued).
810  * @param tc Task Context.
811  */
812 static void
813 start_test (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
814 {
815   enum GNUNET_MESH_ChannelOption flags;
816   unsigned long i;
817
818   if ((GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason) != 0)
819     return;
820
821   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Start profiler\n");
822
823   flags = GNUNET_MESH_OPTION_DEFAULT;
824   for (i = 0; i < PING_PEERS; i++)
825   {
826
827     peers[i].dest = select_random_peer (&peers[i]);
828     peers[i].ch = GNUNET_MESH_channel_create (peers[i].mesh, NULL,
829                                               &peers[i].dest->id,
830                                               1, flags);
831     if (NULL == peers[i].ch)
832     {
833       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Channel %lu failed\n", i);
834       GNUNET_SCHEDULER_shutdown ();
835       return;
836     }
837     GNUNET_log (GNUNET_ERROR_TYPE_INFO, "%u => %u %p\n",
838                 i, get_index (peers[i].dest), peers[i].ch);
839     peers[i].ping_task = GNUNET_SCHEDULER_add_delayed (delay_ms_rnd (2000),
840                                                        &ping, &peers[i]);
841   }
842   peers_running = TOTAL_PEERS;
843   if (GNUNET_SCHEDULER_NO_TASK != disconnect_task)
844     GNUNET_SCHEDULER_cancel (disconnect_task);
845   disconnect_task =
846     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply(ROUND_TIME,
847                                                                 number_rounds + 1),
848                                   &disconnect_mesh_peers,
849                                   (void *) __LINE__);
850   GNUNET_SCHEDULER_add_delayed (ROUND_TIME, &next_rnd, NULL);
851 }
852
853
854 /**
855  * Callback to be called when the requested peer information is available
856  *
857  * @param cls the closure from GNUNET_TESTBED_peer_get_information()
858  * @param op the operation this callback corresponds to
859  * @param pinfo the result; will be NULL if the operation has failed
860  * @param emsg error message if the operation has failed;
861  *             NULL if the operation is successfull
862  */
863 static void
864 peer_id_cb (void *cls,
865        struct GNUNET_TESTBED_Operation *op,
866        const struct GNUNET_TESTBED_PeerInformation *pinfo,
867        const char *emsg)
868 {
869   long n = (long) cls;
870
871   if (NULL == pinfo || NULL != emsg)
872   {
873     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "pi_cb: %s\n", emsg);
874     abort_test (__LINE__);
875     return;
876   }
877   peers[n].id = *(pinfo->result.id);
878   GNUNET_log (GNUNET_ERROR_TYPE_INFO, " %u  id: %s\n",
879               n, GNUNET_i2s (&peers[n].id));
880   GNUNET_break (GNUNET_OK ==
881                 GNUNET_CONTAINER_multipeermap_put (ids, &peers[n].id, &peers[n],
882                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
883
884   GNUNET_TESTBED_operation_done (peers[n].op);
885   peers[n].op = NULL;
886
887   p_ids++;
888   if (p_ids < TOTAL_PEERS)
889     return;
890   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Got all IDs, starting profiler\n");
891   test_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
892                                             &start_test, NULL);
893 }
894
895 /**
896  * test main: start test when all peers are connected
897  *
898  * @param cls Closure.
899  * @param ctx Argument to give to GNUNET_MESH_TEST_cleanup on test end.
900  * @param num_peers Number of peers that are running.
901  * @param testbed_peers Array of peers.
902  * @param meshes Handle to each of the MESHs of the peers.
903  */
904 static void
905 tmain (void *cls,
906        struct GNUNET_MESH_TEST_Context *ctx,
907        unsigned int num_peers,
908        struct GNUNET_TESTBED_Peer **testbed_peers,
909        struct GNUNET_MESH_Handle **meshes)
910 {
911   unsigned long i;
912
913   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "test main\n");
914   test_ctx = ctx;
915   GNUNET_assert (TOTAL_PEERS > 2 * PING_PEERS);
916   GNUNET_assert (TOTAL_PEERS == num_peers);
917   peers_running = num_peers;
918   testbed_handles = testbed_peers;
919   disconnect_task = GNUNET_SCHEDULER_add_delayed (SHORT_TIME,
920                                                   &disconnect_mesh_peers,
921                                                   (void *) __LINE__);
922   shutdown_handle = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
923                                                   &shutdown_task, NULL);
924   for (i = 0; i < TOTAL_PEERS; i++)
925   {
926     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "requesting id %ld\n", i);
927     peers[i].up = GNUNET_YES;
928     peers[i].mesh = meshes[i];
929     peers[i].op =
930       GNUNET_TESTBED_peer_get_information (testbed_handles[i],
931                                            GNUNET_TESTBED_PIT_IDENTITY,
932                                            &peer_id_cb, (void *) i);
933   }
934   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "requested peer ids\n");
935   /* Continues from pi_cb -> do_test */
936 }
937
938
939 /**
940  * Main: start profiler.
941  */
942 int
943 main (int argc, char *argv[])
944 {
945   static uint32_t ports[2];
946   const char *config_file;
947
948   config_file = "profiler.conf";
949
950   ids = GNUNET_CONTAINER_multipeermap_create (2 * TOTAL_PEERS, GNUNET_YES);
951   GNUNET_assert (NULL != ids);
952   p_ids = 0;
953   test_finished = GNUNET_NO;
954   ports[0] = 1;
955   ports[1] = 0;
956   GNUNET_MESH_TEST_run ("mesh-profiler", config_file, TOTAL_PEERS,
957                         &tmain, NULL, /* tmain cls */
958                         &incoming_channel, &channel_cleaner,
959                         handlers, ports);
960
961   return 0;
962 }
963
964 /* end of gnunet-mesh-profiler.c */
965