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