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