- changes to round system, stats collection
[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, 10)
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  * Ratio of peers active. First round always is 1.0.
67  */
68 static float rounds[] = {0.8, 0.7, 0.6, 0.5, 0.0};
69
70 /**
71  * Total number of rounds.
72  */
73 static const unsigned int number_rounds = sizeof(rounds)/sizeof(rounds[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, "ROUND %u PEER %u: %f, PINGS: %u, PONGS: %u\n",
275                i, j, ((float)peer->sum_delay[i])/peer->pongs[i],
276                peer->pings[i], peer->pongs[i]);
277     }
278   }
279 }
280
281
282 /**
283  * Shut down peergroup, clean up.
284  *
285  * @param cls Closure (unused).
286  * @param tc Task Context.
287  */
288 static void
289 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
290 {
291   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Ending test.\n");
292   shutdown_handle = GNUNET_SCHEDULER_NO_TASK;
293 }
294
295
296 /**
297  * Disconnect from mesh services af all peers, call shutdown.
298  *
299  * @param cls Closure (unused).
300  * @param tc Task Context.
301  */
302 static void
303 disconnect_mesh_peers (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
304 {
305   long line = (long) cls;
306   unsigned int i;
307
308   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
309               "disconnecting mesh service, called from line %ld\n", line);
310   disconnect_task = GNUNET_SCHEDULER_NO_TASK;
311   for (i = 0; i < TOTAL_PEERS; i++)
312   {
313     if (NULL != peers[i].op)
314       GNUNET_TESTBED_operation_done (peers[i].op);
315
316     if (peers[i].up != GNUNET_YES)
317       continue;
318
319     if (NULL != peers[i].ch)
320     {
321       GNUNET_log (GNUNET_ERROR_TYPE_INFO, "%u: channel %p\n", i, peers[i].ch);
322       GNUNET_MESH_channel_destroy (peers[i].ch);
323     }
324     if (NULL != peers[i].incoming_ch)
325     {
326       GNUNET_log (GNUNET_ERROR_TYPE_INFO, "%u: incoming channel %p\n",
327                   i, peers[i].incoming_ch);
328       GNUNET_MESH_channel_destroy (peers[i].incoming_ch);
329     }
330   }
331   GNUNET_MESH_TEST_cleanup (test_ctx);
332   if (GNUNET_SCHEDULER_NO_TASK != shutdown_handle)
333   {
334     GNUNET_SCHEDULER_cancel (shutdown_handle);
335   }
336   shutdown_handle = GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
337 }
338
339
340 /**
341  * Finish test normally: schedule disconnect and shutdown
342  *
343  * @param line Line in the code the abort is requested from (__LINE__).
344  */
345 static void
346 abort_test (long line)
347 {
348   if (disconnect_task != GNUNET_SCHEDULER_NO_TASK)
349   {
350     GNUNET_SCHEDULER_cancel (disconnect_task);
351     disconnect_task = GNUNET_SCHEDULER_add_now (&disconnect_mesh_peers,
352                                                 (void *) line);
353   }
354 }
355
356 /**
357  * Stats callback. Finish the stats testbed operation and when all stats have
358  * been iterated, shutdown the test.
359  *
360  * @param cls closure
361  * @param op the operation that has been finished
362  * @param emsg error message in case the operation has failed; will be NULL if
363  *          operation has executed successfully.
364  */
365 static void
366 stats_cont (void *cls, struct GNUNET_TESTBED_Operation *op, const char *emsg)
367 {
368   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "... collecting statistics done.\n");
369   GNUNET_TESTBED_operation_done (stats_op);
370
371   if (GNUNET_SCHEDULER_NO_TASK != disconnect_task)
372     GNUNET_SCHEDULER_cancel (disconnect_task);
373   disconnect_task = GNUNET_SCHEDULER_add_now (&disconnect_mesh_peers,
374                                               (void *) __LINE__);
375
376 }
377
378
379 /**
380  * Process statistic values.
381  *
382  * @param cls closure
383  * @param peer the peer the statistic belong to
384  * @param subsystem name of subsystem that created the statistic
385  * @param name the name of the datum
386  * @param value the current value
387  * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
388  * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
389  */
390 static int
391 stats_iterator (void *cls, const struct GNUNET_TESTBED_Peer *peer,
392                 const char *subsystem, const char *name,
393                 uint64_t value, int is_persistent)
394 {
395   uint32_t i;
396
397   i = GNUNET_TESTBED_get_index (peer);
398   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, " STATS %u - %s [%s]: %llu\n",
399               i, subsystem, name, value);
400
401   return GNUNET_OK;
402 }
403
404
405 /**
406  * Task check that keepalives were sent and received.
407  *
408  * @param cls Closure (NULL).
409  * @param tc Task Context.
410  */
411 static void
412 collect_stats (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
413 {
414   if ((GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason) != 0)
415     return;
416
417   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Start collecting statistics...\n");
418   stats_op = GNUNET_TESTBED_get_statistics (TOTAL_PEERS, testbed_handles,
419                                             NULL, NULL,
420                                             stats_iterator, stats_cont, NULL);
421 }
422
423
424 /**
425  * @brief Finish profiler normally. Signal finish and start collecting stats.
426  *
427  * @param cls Closure (unused).
428  * @param tc Task context.
429  */
430 static void
431 finish_profiler (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
432 {
433   if ((GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason) != 0)
434     return;
435
436   test_finished = GNUNET_YES;
437   show_end_data();
438   GNUNET_SCHEDULER_add_now (&collect_stats, NULL);
439 }
440
441 /**
442  * Set the total number of running peers.
443  *
444  * @param target Desired number of running peers.
445  */
446 static void
447 adjust_running_peers (unsigned int target)
448 {
449   struct GNUNET_TESTBED_Operation *op;
450   unsigned int delta;
451   unsigned int run;
452   unsigned int i;
453   unsigned int r;
454
455   GNUNET_assert (target <= TOTAL_PEERS);
456
457   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "adjust peers to %u\n", target);
458   if (target > peers_running)
459   {
460     delta = target - peers_running;
461     run = GNUNET_YES;
462   }
463   else
464   {
465     delta = peers_running - target;
466     run = GNUNET_NO;
467   }
468
469   for (i = 0; i < delta; i++)
470   {
471     do {
472       r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
473                                     TOTAL_PEERS - PING_PEERS);
474       r += PING_PEERS;
475     } while (peers[r].up == run || NULL != peers[r].incoming);
476     GNUNET_log (GNUNET_ERROR_TYPE_INFO, "St%s peer %u: %s\n",
477                 run ? "arting" : "opping", r, GNUNET_i2s (&peers[r].id));
478
479     if (GNUNET_SCHEDULER_NO_TASK != peers[r].ping_task)
480       GNUNET_SCHEDULER_cancel (peers[r].ping_task);
481     peers[r].ping_task = GNUNET_SCHEDULER_NO_TASK;
482
483     peers[r].up = run;
484
485     if (NULL != peers[r].ch)
486       GNUNET_MESH_channel_destroy (peers[r].ch);
487     peers[r].ch = NULL;
488     if (NULL != peers[r].dest)
489     {
490       if (NULL != peers[r].dest->incoming_ch)
491         GNUNET_MESH_channel_destroy (peers[r].dest->incoming_ch);
492       peers[r].dest->incoming_ch = NULL;
493     }
494
495     op = GNUNET_TESTBED_peer_manage_service (&peers[r], testbed_handles[r],
496                                              "mesh", NULL, NULL, run);
497     GNUNET_break (NULL != op);
498     peers_running += run ? 1 : -1;
499     GNUNET_assert (peers_running > 0);
500   }
501 }
502
503
504 /**
505  * @brief Move to next round.
506  *
507  * @param cls Closure (round #).
508  * @param tc Task context.
509  */
510 static void
511 next_rnd (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
512 {
513   if ((GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason) != 0)
514     return;
515
516   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "ROUND %ld\n", current_round);
517   if (0.0 == rounds[current_round])
518   {
519     GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Finishing\n");
520     GNUNET_SCHEDULER_add_now (&finish_profiler, NULL);
521     return;
522   }
523   adjust_running_peers (rounds[current_round] * TOTAL_PEERS);
524   current_round++;
525
526   GNUNET_SCHEDULER_add_delayed (ROUND_TIME, &next_rnd, NULL);
527 }
528
529
530 /**
531  * Transmit ping callback.
532  *
533  * @param cls Closure (peer for PING, NULL for PONG).
534  * @param size Size of the tranmist buffer.
535  * @param buf Pointer to the beginning of the buffer.
536  *
537  * @return Number of bytes written to buf.
538  */
539 static size_t
540 tmt_rdy_ping (void *cls, size_t size, void *buf);
541
542
543 /**
544  * Transmit pong callback.
545  *
546  * @param cls Closure (copy of PING message, to be freed).
547  * @param size Size of the buffer we have.
548  * @param buf Buffer to copy data to.
549  */
550 static size_t
551 tmt_rdy_pong (void *cls, size_t size, void *buf)
552 {
553   struct MeshPingMessage *ping = cls;
554   struct MeshPingMessage *pong;
555
556   if (0 == size || NULL == buf)
557   {
558     GNUNET_free (ping);
559     return 0;
560   }
561   pong = (struct MeshPingMessage *) buf;
562   memcpy (pong, ping, sizeof (*ping));
563   pong->header.type = htons (PONG);
564
565   GNUNET_free (ping);
566   return sizeof (*ping);
567 }
568
569
570 /**
571  * @brief Send a ping to destination
572  *
573  * @param cls Closure (peer).
574  * @param tc Task context.
575  */
576 static void
577 ping (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
578 {
579   struct MeshPeer *peer = (struct MeshPeer *) cls;
580
581   peer->ping_task = GNUNET_SCHEDULER_NO_TASK;
582
583   if ((GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason) != 0
584       || GNUNET_YES == test_finished)
585     return;
586
587   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "%u -> %u (%u)\n",
588               get_index (peer), get_index (peer->dest), peer->data_sent);
589
590   GNUNET_MESH_notify_transmit_ready (peer->ch, GNUNET_NO,
591                                      GNUNET_TIME_UNIT_FOREVER_REL,
592                                      sizeof (struct MeshPingMessage),
593                                      &tmt_rdy_ping, peer);
594 }
595
596 /**
597  * @brief Reply with a pong to origin.
598  *
599  * @param cls Closure (peer).
600  * @param tc Task context.
601  */
602 static void
603 pong (struct GNUNET_MESH_Channel *channel, const struct MeshPingMessage *ping)
604 {
605   struct MeshPingMessage *copy;
606
607   copy = GNUNET_new (struct MeshPingMessage);
608   memcpy (copy, ping, sizeof (*ping));
609   GNUNET_MESH_notify_transmit_ready (channel, GNUNET_NO,
610                                      GNUNET_TIME_UNIT_FOREVER_REL,
611                                      sizeof (struct MeshPingMessage),
612                                      &tmt_rdy_pong, copy);
613 }
614
615
616 /**
617  * Transmit ping callback
618  *
619  * @param cls Closure (peer).
620  * @param size Size of the buffer we have.
621  * @param buf Buffer to copy data to.
622  */
623 static size_t
624 tmt_rdy_ping (void *cls, size_t size, void *buf)
625 {
626   struct MeshPeer *peer = (struct MeshPeer *) cls;
627   struct MeshPingMessage *msg = buf;
628
629   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "tmt_rdy called, filling buffer\n");
630   if (size < sizeof (struct MeshPingMessage) || NULL == buf)
631   {
632     GNUNET_break (0);
633     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
634                 "size %u, buf %p, data_sent %u, data_received %u\n",
635                 size, buf, peer->data_sent, peer->data_received);
636
637     return 0;
638   }
639   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending: msg %d\n", peer->data_sent);
640   msg->header.size = htons (size);
641   msg->header.type = htons (PING);
642   msg->counter = htonl (peer->data_sent++);
643   msg->round_number = htonl (current_round);
644   msg->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
645   peer->pings[current_round]++;
646   peer->ping_task = GNUNET_SCHEDULER_add_delayed (delay_ms_rnd (PING_PERIOD),
647                                                   &ping, peer);
648
649   return sizeof (struct MeshPingMessage);
650 }
651
652
653 /**
654  * Function is called whenever a PING message is received.
655  *
656  * @param cls closure (peer #, set from GNUNET_MESH_connect)
657  * @param channel connection to the other end
658  * @param channel_ctx place to store local state associated with the channel
659  * @param message the actual message
660  * @return GNUNET_OK to keep the connection open,
661  *         GNUNET_SYSERR to close it (signal serious error)
662  */
663 int
664 ping_handler (void *cls, struct GNUNET_MESH_Channel *channel,
665               void **channel_ctx,
666               const struct GNUNET_MessageHeader *message)
667 {
668   long n = (long) cls;
669
670   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%u got PING\n", n);
671   GNUNET_MESH_receive_done (channel);
672   if (GNUNET_NO == test_finished)
673     pong (channel, (struct MeshPingMessage *) message);
674
675   return GNUNET_OK;
676 }
677
678
679 /**
680  * Function is called whenever a PONG message is received.
681  *
682  * @param cls closure (peer #, set from GNUNET_MESH_connect)
683  * @param channel connection to the other end
684  * @param channel_ctx place to store local state associated with the channel
685  * @param message the actual message
686  * @return GNUNET_OK to keep the connection open,
687  *         GNUNET_SYSERR to close it (signal serious error)
688  */
689 int
690 pong_handler (void *cls, struct GNUNET_MESH_Channel *channel,
691               void **channel_ctx,
692               const struct GNUNET_MessageHeader *message)
693 {
694   long n = (long) cls;
695   struct MeshPeer *peer;
696   struct MeshPingMessage *msg;
697   struct GNUNET_TIME_Absolute send_time;
698   struct GNUNET_TIME_Relative latency;
699   unsigned int ping_round;
700
701   GNUNET_MESH_receive_done (channel);
702   peer = &peers[n];
703
704   msg = (struct MeshPingMessage *) message;
705
706   send_time = GNUNET_TIME_absolute_ntoh (msg->timestamp);
707   latency = GNUNET_TIME_absolute_get_duration (send_time);
708   ping_round = ntohl (msg->round_number);
709   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "%u <- %u (%u) latency: %s\n",
710               get_index (peer), get_index (peer->dest), ntohl (msg->counter),
711               GNUNET_STRINGS_relative_time_to_string (latency, GNUNET_NO));
712   peer->sum_delay[ping_round] += latency.rel_value_us;
713   peer->pongs[ping_round]++;
714
715   return GNUNET_OK;
716 }
717
718
719 /**
720  * Handlers, for diverse services
721  */
722 static struct GNUNET_MESH_MessageHandler handlers[] = {
723   {&ping_handler, PING, sizeof (struct MeshPingMessage)},
724   {&pong_handler, PONG, sizeof (struct MeshPingMessage)},
725   {NULL, 0, 0}
726 };
727
728
729 /**
730  * Method called whenever another peer has added us to a channel
731  * the other peer initiated.
732  *
733  * @param cls Closure.
734  * @param channel New handle to the channel.
735  * @param initiator Peer that started the channel.
736  * @param port Port this channel is connected to.
737  * @param options channel option flags
738  * @return Initial channel context for the channel
739  *         (can be NULL -- that's not an error).
740  */
741 static void *
742 incoming_channel (void *cls, struct GNUNET_MESH_Channel *channel,
743                  const struct GNUNET_PeerIdentity *initiator,
744                  uint32_t port, enum GNUNET_MESH_ChannelOption options)
745 {
746   long n = (long) cls;
747   struct MeshPeer *peer;
748
749   peer = GNUNET_CONTAINER_multipeermap_get (ids, initiator);
750   GNUNET_assert (NULL != peer);
751   GNUNET_assert (peer == peers[n].incoming);
752   GNUNET_assert (peer->dest == &peers[n]);
753   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "%u <= %u %p\n",
754               n, get_index (peer), channel);
755   peers[n].incoming_ch = channel;
756
757   return NULL;
758 }
759
760 /**
761  * Function called whenever an inbound channel is destroyed.  Should clean up
762  * any associated state.
763  *
764  * @param cls closure (set from GNUNET_MESH_connect)
765  * @param channel connection to the other end (henceforth invalid)
766  * @param channel_ctx place where local state associated
767  *                   with the channel is stored
768  */
769 static void
770 channel_cleaner (void *cls, const struct GNUNET_MESH_Channel *channel,
771                  void *channel_ctx)
772 {
773   long n = (long) cls;
774   struct MeshPeer *peer = &peers[n];
775
776   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
777               "Channel %p disconnected at peer %ld\n", channel, n);
778   if (peer->ch == channel)
779     peer->ch = NULL;
780 }
781
782
783 static struct MeshPeer *
784 select_random_peer (struct MeshPeer *peer)
785 {
786   unsigned int r;
787
788   do
789   {
790     r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, TOTAL_PEERS);
791   } while (NULL != peers[r].incoming);
792   peers[r].incoming = peer;
793
794   return &peers[r];
795 }
796
797 /**
798  * START THE TEST ITSELF, AS WE ARE CONNECTED TO THE MESH SERVICES.
799  *
800  * Testcase continues when the root receives confirmation of connected peers,
801  * on callback funtion ch.
802  *
803  * @param cls Closure (unsued).
804  * @param tc Task Context.
805  */
806 static void
807 start_test (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
808 {
809   enum GNUNET_MESH_ChannelOption flags;
810   unsigned long i;
811
812   if ((GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason) != 0)
813     return;
814
815   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Start profiler\n");
816
817   flags = GNUNET_MESH_OPTION_DEFAULT;
818   for (i = 0; i < PING_PEERS; i++)
819   {
820
821     peers[i].dest = select_random_peer (&peers[i]);
822     peers[i].ch = GNUNET_MESH_channel_create (peers[i].mesh, NULL,
823                                               &peers[i].dest->id,
824                                               1, flags);
825     if (NULL == peers[i].ch)
826     {
827       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Channel %lu failed\n", i);
828       GNUNET_SCHEDULER_shutdown ();
829       return;
830     }
831     GNUNET_log (GNUNET_ERROR_TYPE_INFO, "%u => %u %p\n",
832                 i, get_index (peers[i].dest), peers[i].ch);
833     peers[i].ping_task = GNUNET_SCHEDULER_add_delayed (delay_ms_rnd (2000),
834                                                        &ping, &peers[i]);
835   }
836   peers_running = TOTAL_PEERS;
837   if (GNUNET_SCHEDULER_NO_TASK != disconnect_task)
838     GNUNET_SCHEDULER_cancel (disconnect_task);
839   disconnect_task =
840     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply(ROUND_TIME,
841                                                                 number_rounds + 1),
842                                   &disconnect_mesh_peers,
843                                   (void *) __LINE__);
844   GNUNET_SCHEDULER_add_delayed (ROUND_TIME, &next_rnd, NULL);
845 }
846
847
848 /**
849  * Callback to be called when the requested peer information is available
850  *
851  * @param cls the closure from GNUNET_TESTBED_peer_get_information()
852  * @param op the operation this callback corresponds to
853  * @param pinfo the result; will be NULL if the operation has failed
854  * @param emsg error message if the operation has failed;
855  *             NULL if the operation is successfull
856  */
857 static void
858 peer_id_cb (void *cls,
859        struct GNUNET_TESTBED_Operation *op,
860        const struct GNUNET_TESTBED_PeerInformation *pinfo,
861        const char *emsg)
862 {
863   long n = (long) cls;
864
865   if (NULL == pinfo || NULL != emsg)
866   {
867     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "pi_cb: %s\n", emsg);
868     abort_test (__LINE__);
869     return;
870   }
871   peers[n].id = *(pinfo->result.id);
872   GNUNET_log (GNUNET_ERROR_TYPE_INFO, " %u  id: %s\n",
873               n, GNUNET_i2s (&peers[n].id));
874   GNUNET_break (GNUNET_OK ==
875                 GNUNET_CONTAINER_multipeermap_put (ids, &peers[n].id, &peers[n],
876                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST));
877
878   GNUNET_TESTBED_operation_done (peers[n].op);
879   peers[n].op = NULL;
880
881   p_ids++;
882   if (p_ids < TOTAL_PEERS)
883     return;
884   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Got all IDs, starting profiler\n");
885   test_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
886                                             &start_test, NULL);
887 }
888
889 /**
890  * test main: start test when all peers are connected
891  *
892  * @param cls Closure.
893  * @param ctx Argument to give to GNUNET_MESH_TEST_cleanup on test end.
894  * @param num_peers Number of peers that are running.
895  * @param testbed_peers Array of peers.
896  * @param meshes Handle to each of the MESHs of the peers.
897  */
898 static void
899 tmain (void *cls,
900        struct GNUNET_MESH_TEST_Context *ctx,
901        unsigned int num_peers,
902        struct GNUNET_TESTBED_Peer **testbed_peers,
903        struct GNUNET_MESH_Handle **meshes)
904 {
905   unsigned long i;
906
907   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "test main\n");
908   test_ctx = ctx;
909   GNUNET_assert (TOTAL_PEERS > 2 * PING_PEERS);
910   GNUNET_assert (TOTAL_PEERS == num_peers);
911   peers_running = num_peers;
912   testbed_handles = testbed_peers;
913   disconnect_task = GNUNET_SCHEDULER_add_delayed (SHORT_TIME,
914                                                   &disconnect_mesh_peers,
915                                                   (void *) __LINE__);
916   shutdown_handle = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
917                                                   &shutdown_task, NULL);
918   for (i = 0; i < TOTAL_PEERS; i++)
919   {
920     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "requesting id %ld\n", i);
921     peers[i].up = GNUNET_YES;
922     peers[i].mesh = meshes[i];
923     peers[i].op =
924       GNUNET_TESTBED_peer_get_information (testbed_handles[i],
925                                            GNUNET_TESTBED_PIT_IDENTITY,
926                                            &peer_id_cb, (void *) i);
927   }
928   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "requested peer ids\n");
929   /* Continues from pi_cb -> do_test */
930 }
931
932
933 /**
934  * Main: start profiler.
935  */
936 int
937 main (int argc, char *argv[])
938 {
939   static uint32_t ports[2];
940   const char *config_file;
941
942   config_file = "profiler.conf";
943
944   ids = GNUNET_CONTAINER_multipeermap_create (2 * TOTAL_PEERS, GNUNET_YES);
945   GNUNET_assert (NULL != ids);
946   p_ids = 0;
947   test_finished = GNUNET_NO;
948   ports[0] = 1;
949   ports[1] = 0;
950   GNUNET_MESH_TEST_run ("mesh-profiler", config_file, TOTAL_PEERS,
951                         &tmain, NULL, /* tmain cls */
952                         &incoming_channel, &channel_cleaner,
953                         handlers, ports);
954
955   return 0;
956 }
957
958 /* end of gnunet-mesh-profiler.c */
959