free in proper place
[oweals/gnunet.git] / src / testing / test_testing_topology.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009 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 testing/test_testing_topology.c
22  * @brief base testcase for testing all the topologies provided
23  */
24 #include "platform.h"
25 #include "gnunet_testing_lib.h"
26 #include "gnunet_core_service.h"
27 #include "gnunet_os_lib.h"
28
29 #define VERBOSE GNUNET_NO
30
31 #define PROGRESS_BARS GNUNET_YES
32
33 #define DELAY_FOR_LOGGING GNUNET_NO
34
35 /**
36  * How long until we fail the whole testcase?
37  */
38 #define TEST_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 240)
39
40 /**
41  * How long until we give up on starting the peers?
42  */
43 #define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 500)
44
45 #define SECONDS_PER_PEER_START 120
46
47 #define DEFAULT_NUM_PEERS 4
48
49 #define MAX_OUTSTANDING_CONNECTIONS 100
50
51 static float fail_percentage = 0.05;
52
53 static int ok;
54
55 static unsigned long long num_peers;
56
57 struct GNUNET_TIME_Relative connect_timeout;
58
59 static unsigned long long connect_attempts;
60
61 static unsigned int topology_connections;
62
63 static unsigned int total_connections;
64
65 static unsigned int failed_connections;
66
67 static unsigned int total_server_connections;
68
69 static unsigned int total_messages_received;
70
71 static unsigned int expected_messages;
72
73 static unsigned int expected_connections;
74
75 static unsigned long long peers_left;
76
77 static struct GNUNET_TESTING_PeerGroup *pg;
78
79 const struct GNUNET_CONFIGURATION_Handle *main_cfg;
80
81 GNUNET_SCHEDULER_TaskIdentifier die_task;
82
83 static char *dotOutFileName;
84
85 static struct GNUNET_TIME_Relative settle_time;
86
87 static FILE *dotOutFile;
88
89 static char *topology_string;
90
91 static char *blacklist_transports;
92
93 static int transmit_ready_scheduled;
94
95 static int transmit_ready_failed;
96
97 static int transmit_ready_called;
98
99 static unsigned int modnum;
100
101 static unsigned int dotnum;
102
103 static enum GNUNET_TESTING_Topology topology;
104
105 static enum GNUNET_TESTING_Topology blacklist_topology = GNUNET_TESTING_TOPOLOGY_NONE;  /* Don't do any blacklisting */
106
107 static enum GNUNET_TESTING_Topology connection_topology = GNUNET_TESTING_TOPOLOGY_NONE; /* NONE actually means connect all allowed peers */
108
109 static enum GNUNET_TESTING_TopologyOption connect_topology_option =
110   GNUNET_TESTING_TOPOLOGY_OPTION_ALL;
111
112 static double connect_topology_option_modifier = 0.0;
113
114 static char *test_directory;
115
116 #define MTYPE 12345
117
118 struct GNUNET_TestMessage
119 {
120   /**
121    * Header of the message
122    */
123   struct GNUNET_MessageHeader header;
124
125   /**
126    * Unique identifier for this message.
127    */
128   uint32_t uid;
129 };
130
131 struct TestMessageContext
132 {
133   /* This is a linked list */
134   struct TestMessageContext *next;
135
136   /* Handle to the sending peer core */
137   struct GNUNET_CORE_Handle *peer1handle;
138
139   /* Handle to the receiving peer core */
140   struct GNUNET_CORE_Handle *peer2handle;
141
142   /* Handle to the sending peer daemon */
143   struct GNUNET_TESTING_Daemon *peer1;
144
145   /* Handle to the receiving peer daemon */
146   struct GNUNET_TESTING_Daemon *peer2;
147
148   /* Identifier for this message, so we don't disconnect other peers! */
149   uint32_t uid;
150
151   /* Has peer1 been notified already of a connection to peer2? */
152   int peer1notified;
153
154   /* Has the core of peer2 been connected already? */
155   int peer2connected;
156
157   /* Task for disconnecting cores, allow task to be cancelled on shutdown */
158   GNUNET_SCHEDULER_TaskIdentifier disconnect_task;
159
160 };
161
162 static struct TestMessageContext *test_messages;
163
164 /**
165  * Check whether peers successfully shut down.
166  */
167 void
168 shutdown_callback (void *cls, const char *emsg)
169 {
170   if (emsg != NULL)
171     {
172 #if VERBOSE
173       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Shutdown of peers failed!\n");
174 #endif
175       if (ok == 0)
176         ok = 666;
177     }
178   else
179     {
180 #if VERBOSE
181       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
182                   "All peers successfully shut down!\n");
183 #endif
184     }
185 }
186
187 #if DELAY_FOR_LOGGING
188 static void
189 gather_log_data ()
190 {
191   char *peer_number;
192   char *connect_number;
193   struct GNUNET_OS_Process *mem_process;
194   GNUNET_asprintf (&peer_number, "%llu", num_peers);
195   GNUNET_asprintf (&connect_number, "%llu", expected_connections);
196   mem_process = GNUNET_OS_start_process (NULL, NULL, "./memsize.pl",
197                                          "memsize.pl", "totals.txt",
198                                          peer_number, connect_number, NULL);
199   GNUNET_OS_process_wait (mem_process);
200   GNUNET_OS_process_close (mem_process);
201   mem_process = NULL;
202 }
203
204 #endif
205
206 static void
207 finish_testing ()
208 {
209   GNUNET_assert (pg != NULL);
210   struct TestMessageContext *pos;
211   struct TestMessageContext *free_pos;
212 #if VERBOSE
213   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
214               "Called finish testing, stopping daemons.\n");
215 #endif
216
217   pos = test_messages;
218   while (pos != NULL)
219     {
220       if (pos->peer1handle != NULL)
221         {
222           GNUNET_CORE_disconnect (pos->peer1handle);
223           pos->peer1handle = NULL;
224         }
225       if (pos->peer2handle != NULL)
226         {
227           GNUNET_CORE_disconnect (pos->peer2handle);
228           pos->peer2handle = NULL;
229         }
230       free_pos = pos;
231       pos = pos->next;
232       if (free_pos->disconnect_task != GNUNET_SCHEDULER_NO_TASK)
233         {
234           GNUNET_SCHEDULER_cancel (free_pos->disconnect_task);
235         }
236       GNUNET_free (free_pos);
237     }
238 #if VERBOSE
239   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
240               "Transmit_ready's scheduled %d, failed %d, transmit_ready's called %d\n",
241               transmit_ready_scheduled, transmit_ready_failed,
242               transmit_ready_called);
243 #endif
244
245 #if VERBOSE
246   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Calling daemons_stop\n");
247 #endif
248   GNUNET_TESTING_daemons_stop (pg, TIMEOUT, &shutdown_callback, NULL);
249
250   if (dotOutFile != NULL)
251     {
252       fprintf (dotOutFile, "}");
253       fclose (dotOutFile);
254     }
255
256   ok = 0;
257 }
258
259
260 static void
261 disconnect_cores (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
262 {
263   struct TestMessageContext *pos = cls;
264
265   /* Disconnect from the respective cores */
266 #if VERBOSE > 1
267   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
268               "Disconnecting from peer 1 `%4s'\n",
269               GNUNET_i2s (&pos->peer1->id));
270 #endif
271   if (pos->peer1handle != NULL)
272     GNUNET_CORE_disconnect (pos->peer1handle);
273 #if VERBOSE > 1
274   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
275               "Disconnecting from peer 2 `%4s'\n",
276               GNUNET_i2s (&pos->peer2->id));
277 #endif
278   if (pos->peer2handle != NULL)
279     GNUNET_CORE_disconnect (pos->peer2handle);
280   /* Set handles to NULL so test case can be ended properly */
281   pos->peer1handle = NULL;
282   pos->peer2handle = NULL;
283   pos->disconnect_task = GNUNET_SCHEDULER_NO_TASK;
284   /* Decrement total connections so new can be established */
285   total_server_connections -= 2;
286 }
287
288 #if DO_STATS
289 static void
290 stats_finished (void *cls, int result)
291 {
292   GNUNET_SCHEDULER_add_now (&finish_testing, NULL);
293 }
294
295 /**
296  * Callback function to process statistic values.
297  *
298  * @param cls closure
299  * @param peer the peer the statistics belong to
300  * @param subsystem name of subsystem that created the statistic
301  * @param name the name of the datum
302  * @param value the current value
303  * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
304  * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
305  */
306 static int
307 stats_print (void *cls,
308              const struct GNUNET_PeerIdentity *peer,
309              const char *subsystem,
310              const char *name, uint64_t value, int is_persistent)
311 {
312   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s:%s:%s -- %llu\n",
313               GNUNET_i2s (peer), subsystem, name, value);
314   return GNUNET_OK;
315 }
316 #endif
317
318 static void
319 topology_cb (void *cls,
320              const struct GNUNET_PeerIdentity *first,
321              const struct GNUNET_PeerIdentity *second, const char *emsg)
322 {
323   FILE *outfile = cls;
324   if (first != NULL)
325     {
326       if (outfile != NULL)
327         {
328           fprintf (outfile, "\t\"%s\" -- ", GNUNET_i2s (first));
329           fprintf (outfile, "\"%s\";\n", GNUNET_i2s (second));
330         }
331       topology_connections++;
332     }
333   else
334     {
335       fprintf (stderr,
336                "Finished iterating over topology, %d total connections!\n",
337                topology_connections);
338       if (outfile != NULL)
339         {
340           fprintf (outfile, "}\n");
341           fclose (outfile);
342 #if DO_STATS
343           GNUNET_TESTING_get_statistics (pg, &stats_finished, &stats_print,
344                                          NULL);
345 #endif
346           GNUNET_SCHEDULER_add_now (&finish_testing, NULL);
347         }
348     }
349 }
350
351 static int
352 process_mtype (void *cls,
353                const struct GNUNET_PeerIdentity *peer,
354                const struct GNUNET_MessageHeader *message,
355                const struct GNUNET_TRANSPORT_ATS_Information *atsi)
356 {
357   char *dotOutFileNameFinished;
358   FILE *dotOutFileFinished;
359   struct TestMessageContext *pos = cls;
360   struct GNUNET_TestMessage *msg = (struct GNUNET_TestMessage *) message;
361   if (pos->uid != ntohl (msg->uid))
362     return GNUNET_OK;
363
364 #if PROGRESS_BARS
365   if ((total_messages_received) % modnum == 0)
366     {
367       if (total_messages_received == 0)
368         fprintf (stdout, "0%%");
369       else
370         fprintf (stdout, "%d%%",
371                  (int) (((float) total_messages_received /
372                          expected_messages) * 100));
373
374     }
375   else if (total_messages_received % dotnum == 0)
376     {
377       fprintf (stdout, ".");
378     }
379   fflush (stdout);
380 #endif
381
382   total_messages_received++;
383
384 #if VERBOSE > 1
385   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
386               "Received message from `%4s', type %d.\n", GNUNET_i2s (peer),
387               ntohs (message->type));
388   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
389               "Total messages received %d, expected %d.\n",
390               total_messages_received, expected_messages);
391 #endif
392
393   if (total_messages_received == expected_messages)
394     {
395 #if PROGRESS_BARS
396       fprintf (stdout, "100%%]\n");
397 #endif
398       GNUNET_SCHEDULER_cancel (die_task);
399       GNUNET_asprintf (&dotOutFileNameFinished, "%s.dot", "final_topology");
400       dotOutFileFinished = fopen (dotOutFileNameFinished, "w");
401       GNUNET_free (dotOutFileNameFinished);
402       if (dotOutFileFinished != NULL)
403         {
404           fprintf (dotOutFileFinished, "strict graph G {\n");
405         }
406       topology_connections = 0;
407       GNUNET_TESTING_get_topology (pg, &topology_cb, dotOutFileFinished);
408       //GNUNET_SCHEDULER_add_now (&finish_testing, NULL);
409     }
410   else
411     {
412       pos->disconnect_task =
413         GNUNET_SCHEDULER_add_now (&disconnect_cores, pos);
414     }
415
416   return GNUNET_OK;
417 }
418
419 static void
420 end_badly (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
421 {
422   char *msg = cls;
423   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
424               "End badly was called (%s)... stopping daemons.\n", msg);
425   struct TestMessageContext *pos;
426   struct TestMessageContext *free_pos;
427
428   pos = test_messages;
429   while (pos != NULL)
430     {
431       if (pos->peer1handle != NULL)
432         {
433           GNUNET_CORE_disconnect (pos->peer1handle);
434           pos->peer1handle = NULL;
435         }
436       if (pos->peer2handle != NULL)
437         {
438           GNUNET_CORE_disconnect (pos->peer2handle);
439           pos->peer2handle = NULL;
440         }
441       free_pos = pos;
442       pos = pos->next;
443       GNUNET_free (free_pos);
444     }
445
446 #if VERBOSE
447   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
448               "Transmit_ready's scheduled %d, failed %d, transmit_ready's called %d\n",
449               transmit_ready_scheduled, transmit_ready_failed,
450               transmit_ready_called);
451   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
452               "Total messages received %d, expected %d.\n",
453               total_messages_received, expected_messages);
454 #endif
455
456   if (pg != NULL)
457     {
458       GNUNET_TESTING_daemons_stop (pg, TIMEOUT, &shutdown_callback, NULL);
459       ok = 7331;                /* Opposite of leet */
460     }
461   else
462     ok = 401;                   /* Never got peers started */
463
464   if (dotOutFile != NULL)
465     {
466       fprintf (dotOutFile, "}");
467       fclose (dotOutFile);
468     }
469 }
470
471 static size_t
472 transmit_ready (void *cls, size_t size, void *buf)
473 {
474   struct GNUNET_TestMessage *m;
475   struct TestMessageContext *pos = cls;
476
477   GNUNET_assert (buf != NULL);
478   m = (struct GNUNET_TestMessage *) buf;
479   m->header.type = htons (MTYPE);
480   m->header.size = htons (sizeof (struct GNUNET_TestMessage));
481   m->uid = htonl (pos->uid);
482   transmit_ready_called++;
483 #if VERBOSE > 1
484   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
485               "transmit ready for peer %s\ntransmit_ready's scheduled %d, transmit_ready's called %d\n",
486               GNUNET_i2s (&pos->peer1->id), transmit_ready_scheduled,
487               transmit_ready_called);
488 #endif
489   return sizeof (struct GNUNET_TestMessage);
490 }
491
492
493 static struct GNUNET_CORE_MessageHandler no_handlers[] = {
494   {NULL, 0, 0}
495 };
496
497 static struct GNUNET_CORE_MessageHandler handlers[] = {
498   {&process_mtype, MTYPE, sizeof (struct GNUNET_TestMessage)},
499   {NULL, 0, 0}
500 };
501
502 static void
503 init_notify_peer2 (void *cls,
504                    struct GNUNET_CORE_Handle *server,
505                    const struct GNUNET_PeerIdentity *my_identity,
506                    const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
507                    *publicKey)
508 {
509   struct TestMessageContext *pos = cls;
510
511   total_server_connections++;
512
513   pos->peer2connected = GNUNET_YES;
514   if (pos->peer1notified == GNUNET_YES) /* Peer 1 has been notified of connection to peer 2 */
515     {
516 #if VERBOSE > 1
517       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
518                   "Scheduling message send to peer `%s' from peer `%s' (init_notify_peer2)\n",
519                   GNUNET_i2s (my_identity), GNUNET_h2s(&pos->peer1->id.hashPubKey));
520 #endif
521       if (NULL == GNUNET_CORE_notify_transmit_ready (pos->peer1handle,
522                                                      0,
523                                                      TIMEOUT,
524                                                      &pos->peer2->id,
525                                                      sizeof (struct
526                                                              GNUNET_TestMessage),
527                                                      &transmit_ready, pos))
528         {
529           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
530                       "RECEIVED NULL when asking core (1) for transmission to peer `%4s'\n",
531                       GNUNET_i2s (&pos->peer2->id));
532           transmit_ready_failed++;
533         }
534       else
535         {
536           transmit_ready_scheduled++;
537         }
538     }
539 }
540
541 /**
542  * Method called whenever a given peer connects.
543  *
544  * @param cls closure
545  * @param peer peer identity this notification is about
546  * @param atsi performance data for the connection
547  */
548 static void connect_notify_peers (void *cls,
549                                   const struct
550                                   GNUNET_PeerIdentity *peer,
551                                   const struct GNUNET_TRANSPORT_ATS_Information *atsi)
552 {
553   struct TestMessageContext *pos = cls;
554
555   if (0 == memcmp(peer, &pos->peer2->id, sizeof(struct GNUNET_PeerIdentity)))
556     {
557       pos->peer1notified = GNUNET_YES;
558 #if VERBOSE > 1
559       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
560                 "Peer `%s' notified of connection to peer `%s'\n",
561                 GNUNET_i2s (&pos->peer1->id), GNUNET_h2s(&peer->hashPubKey));
562 #endif
563     }
564   else
565     return;
566
567   if (pos->peer2connected == GNUNET_YES) /* Already connected and notified of connection, send message! */
568     {
569 #if VERBOSE > 1
570       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
571                 "Scheduling message send to peer `%s' from peer `%s' (init_notify_peer2)\n",
572                 GNUNET_i2s (&pos->peer2->id), GNUNET_h2s(&pos->peer1->id.hashPubKey));
573 #endif
574       if (NULL == GNUNET_CORE_notify_transmit_ready (pos->peer1handle,
575                                                      0,
576                                                      TIMEOUT,
577                                                      &pos->peer2->id,
578                                                      sizeof (struct
579                                                              GNUNET_TestMessage),
580                                                      &transmit_ready, pos))
581         {
582           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
583                       "RECEIVED NULL when asking core (1) for transmission to peer `%4s'\n",
584                       GNUNET_i2s (&pos->peer2->id));
585           transmit_ready_failed++;
586         }
587       else
588         {
589           transmit_ready_scheduled++;
590         }
591     }
592 }
593
594 static void
595 init_notify_peer1 (void *cls,
596                    struct GNUNET_CORE_Handle *server,
597                    const struct GNUNET_PeerIdentity *my_identity,
598                    const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
599                    *publicKey)
600 {
601   struct TestMessageContext *pos = cls;
602   total_server_connections++;
603
604 #if VERBOSE > 1
605   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
606               "Core connection to `%4s' established, setting up handles\n",
607               GNUNET_i2s (my_identity));
608 #endif
609
610   /*
611    * Connect to the receiving peer
612    */
613   pos->peer2handle = GNUNET_CORE_connect (pos->peer2->cfg,
614                                           1,
615                                           pos,
616                                           &init_notify_peer2,
617                                           NULL,
618                                           NULL,
619                                           NULL, NULL,
620                                           GNUNET_YES, NULL, GNUNET_YES,
621                                           handlers);
622
623 }
624
625
626 static void
627 send_test_messages (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
628 {
629   struct TestMessageContext *pos = cls;
630
631   if ((pos == test_messages) && (settle_time.rel_value > 0))
632     {
633       topology_connections = 0;
634       GNUNET_TESTING_get_topology (pg, &topology_cb, NULL);
635     }
636   if ((tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN) || (cls == NULL))
637     return;
638
639   if (die_task == GNUNET_SCHEDULER_NO_TASK)
640     {
641       die_task = GNUNET_SCHEDULER_add_delayed (TEST_TIMEOUT,
642                                                &end_badly,
643                                                "from send test messages (timeout)");
644     }
645
646   if (total_server_connections >= MAX_OUTSTANDING_CONNECTIONS)
647     {
648       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
649                                     (GNUNET_TIME_UNIT_SECONDS, 1),
650                                     &send_test_messages, pos);
651       return;                   /* Otherwise we'll double schedule messages here! */
652     }
653
654   /*
655    * Connect to the sending peer
656    */
657   pos->peer1handle = GNUNET_CORE_connect (pos->peer1->cfg,
658                                           1,
659                                           pos,
660                                           &init_notify_peer1,
661                                           &connect_notify_peers, NULL,
662                                           NULL,
663                                           NULL,
664                                           GNUNET_NO, NULL, GNUNET_NO,
665                                           no_handlers);
666
667   GNUNET_assert (pos->peer1handle != NULL);
668
669   if (total_server_connections < MAX_OUTSTANDING_CONNECTIONS)
670     {
671       GNUNET_SCHEDULER_add_now (&send_test_messages, pos->next);
672     }
673   else
674     {
675       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
676                                     (GNUNET_TIME_UNIT_SECONDS, 1),
677                                     &send_test_messages, pos->next);
678     }
679 }
680
681
682 void
683 topology_callback (void *cls,
684                    const struct GNUNET_PeerIdentity *first,
685                    const struct GNUNET_PeerIdentity *second,
686                    uint32_t distance,
687                    const struct GNUNET_CONFIGURATION_Handle *first_cfg,
688                    const struct GNUNET_CONFIGURATION_Handle *second_cfg,
689                    struct GNUNET_TESTING_Daemon *first_daemon,
690                    struct GNUNET_TESTING_Daemon *second_daemon,
691                    const char *emsg)
692 {
693   struct TestMessageContext *temp_context;
694   if (emsg == NULL)
695     {
696 #if PROGRESS_BARS
697       if ((total_connections) % modnum == 0)
698         {
699           if (total_connections == 0)
700             fprintf (stdout, "0%%");
701           else
702             fprintf (stdout, "%d%%",
703                      (int) (((float) total_connections /
704                              expected_connections) * 100));
705
706         }
707       else if (total_connections % dotnum == 0)
708         {
709           fprintf (stdout, ".");
710         }
711       fflush (stdout);
712 #endif
713       total_connections++;
714 #if VERBOSE > 1
715       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "connected peer %s to peer %s\n",
716                   first_daemon->shortname, second_daemon->shortname);
717 #endif
718       temp_context = GNUNET_malloc (sizeof (struct TestMessageContext));
719       temp_context->peer1 = first_daemon;
720       temp_context->peer2 = second_daemon;
721       temp_context->next = test_messages;
722       temp_context->uid = total_connections;
723       temp_context->disconnect_task = GNUNET_SCHEDULER_NO_TASK;
724       test_messages = temp_context;
725
726       expected_messages++;
727       if (dotOutFile != NULL)
728         fprintf (dotOutFile, "\tn%s -- n%s;\n", first_daemon->shortname,
729                  second_daemon->shortname);
730     }
731 #if VERBOSE
732   else
733     {
734       failed_connections++;
735       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
736                   "Failed to connect peer %s to peer %s with error :\n%s\n",
737                   first_daemon->shortname, second_daemon->shortname, emsg);
738     }
739 #endif
740
741   if (total_connections == expected_connections)
742     {
743 #if PROGRESS_BARS
744       fprintf (stdout, "100%%]\n");
745 #endif
746 #if VERBOSE
747       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
748                   "Created %d total connections, which is our target number!  Calling send messages.\n",
749                   total_connections);
750 #endif
751       modnum = expected_messages / 4;
752       dotnum = (expected_messages / 50) + 1;
753       if (modnum == 0)
754         modnum = 1;
755       if (dotnum == 0)
756         dotnum = 1;
757       GNUNET_SCHEDULER_cancel (die_task);
758       die_task = GNUNET_SCHEDULER_NO_TASK;
759 #if DELAY_FOR_LOGGING
760       fprintf (stdout, "Sending test messages in 10 seconds.\n");
761       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
762                                     (GNUNET_TIME_UNIT_SECONDS, 10),
763                                     &send_test_messages, test_messages);
764       gather_log_data ();
765 #else
766       if (settle_time.rel_value > 0)
767         {
768           GNUNET_TESTING_get_topology (pg, &topology_cb, NULL);
769         }
770       GNUNET_SCHEDULER_add_delayed (settle_time, &send_test_messages,
771                                     test_messages);
772 #endif
773 #if PROGRESS_BARS
774       fprintf (stdout, "Test message progress: [");
775 #endif
776
777     }
778   else if (total_connections + failed_connections == expected_connections)
779     {
780       if (failed_connections <
781           (unsigned int) (fail_percentage * total_connections))
782         {
783           GNUNET_SCHEDULER_cancel (die_task);
784           die_task = GNUNET_SCHEDULER_NO_TASK;
785           GNUNET_SCHEDULER_add_now (&send_test_messages, test_messages);
786         }
787       else
788         {
789           GNUNET_SCHEDULER_cancel (die_task);
790           die_task =
791             GNUNET_SCHEDULER_add_now (&end_badly,
792                                       "from topology_callback (too many failed connections)");
793         }
794     }
795   else
796     {
797 #if VERBOSE > 1
798       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
799                   "Have %d total connections, %d failed connections, Want %d (at least %d)\n",
800                   total_connections, failed_connections, expected_connections,
801                   expected_connections -
802                   (unsigned int) (fail_percentage * expected_connections));
803 #endif
804     }
805 }
806
807 static void
808 topology_creation_finished (void *cls, const char *emsg)
809 {
810 #if VERBOSE
811   if (emsg == NULL)
812     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
813                 "All topology connections created successfully!\n");
814 #endif
815 }
816
817 static void
818 connect_topology ()
819 {
820   expected_connections = -1;
821   if ((pg != NULL) && (peers_left == 0))
822     {
823       expected_connections =
824         GNUNET_TESTING_connect_topology (pg, connection_topology,
825                                          connect_topology_option,
826                                          connect_topology_option_modifier,
827                                          connect_timeout,
828                                          connect_attempts,
829                                          &topology_creation_finished, NULL);
830 #if PROGRESS_BARS
831       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
832                   "Have %d expected connections\n", expected_connections);
833 #endif
834     }
835
836   GNUNET_SCHEDULER_cancel (die_task);
837   if (expected_connections < 1)
838     {
839       die_task =
840         GNUNET_SCHEDULER_add_now (&end_badly,
841                                   "from connect topology (bad return)");
842       return;
843     }
844
845   die_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
846                                            (GNUNET_TIME_UNIT_SECONDS,
847                                             SECONDS_PER_PEER_START * num_peers),
848                                            &end_badly,
849                                            "from connect topology (timeout)");
850   modnum = expected_connections / 4;
851   dotnum = (expected_connections / 50) + 1;
852   if (modnum == 0)
853     modnum = 1;
854   if (dotnum == 0)
855     dotnum = 1;
856 #if PROGRESS_BARS
857   fprintf (stdout, "Peer connection progress: [");
858 #endif
859 }
860
861 static void
862 create_topology ()
863 {
864   peers_left = num_peers;       /* Reset counter */
865   if (GNUNET_TESTING_create_topology
866       (pg, topology, blacklist_topology,
867        blacklist_transports) != GNUNET_SYSERR)
868     {
869 #if PROGRESS_BARS
870       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
871                   "Topology set up, now starting peers!\n");
872       fprintf (stdout, "Daemon start progress [");
873 #endif
874       GNUNET_TESTING_daemons_continue_startup (pg);
875     }
876   else
877     {
878       GNUNET_SCHEDULER_cancel (die_task);
879       die_task =
880         GNUNET_SCHEDULER_add_now (&end_badly,
881                                   "from create topology (bad return)");
882     }
883   GNUNET_SCHEDULER_cancel (die_task);
884   die_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
885                                            (GNUNET_TIME_UNIT_SECONDS,
886                                             SECONDS_PER_PEER_START * num_peers),
887                                            &end_badly,
888                                            "from continue startup (timeout)");
889 }
890
891
892 static void
893 peers_started_callback (void *cls,
894                         const struct GNUNET_PeerIdentity *id,
895                         const struct GNUNET_CONFIGURATION_Handle *cfg,
896                         struct GNUNET_TESTING_Daemon *d, const char *emsg)
897 {
898   if (emsg != NULL)
899     {
900       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
901                   "Failed to start daemon with error: `%s'\n", emsg);
902       return;
903     }
904   GNUNET_assert (id != NULL);
905 #if VERBOSE > 1
906   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Started daemon %llu out of %llu\n",
907               (num_peers - peers_left) + 1, num_peers);
908 #endif
909 #if PROGRESS_BARS
910   if ((num_peers - peers_left) % modnum == 0)
911     {
912       if (num_peers - peers_left == 0)
913         fprintf (stdout, "0%%");
914       else
915         fprintf (stdout, "%d%%",
916                  (int) (((float) (num_peers - peers_left) /
917                          num_peers) * 100));
918
919     }
920   else if ((num_peers - peers_left) % dotnum == 0)
921     {
922       fprintf (stdout, ".");
923     }
924   fflush (stdout);
925 #endif
926   peers_left--;
927   if (peers_left == 0)
928     {
929 #if PROGRESS_BARS
930       fprintf (stdout, "100%%]\n");
931 #endif
932 #if VERBOSE
933       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
934                   "All %d daemons started, now connecting peers!\n",
935                   num_peers);
936 #endif
937       GNUNET_SCHEDULER_cancel (die_task);
938       /* Set up task in case topology creation doesn't finish
939        * within a reasonable amount of time */
940       die_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
941                                                (GNUNET_TIME_UNIT_MINUTES, 8),
942                                                &end_badly,
943                                                "from peers_started_callback");
944 #if DELAY_FOR_LOGGING
945       fprintf (stdout, "Connecting topology in 10 seconds\n");
946       gather_log_data ();
947       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
948                                     (GNUNET_TIME_UNIT_SECONDS, 10),
949                                     &connect_topology, NULL);
950 #else
951       connect_topology ();
952 #endif
953       ok = 0;
954     }
955 }
956
957 /**
958  * Callback indicating that the hostkey was created for a peer.
959  *
960  * @param cls NULL
961  * @param id the peer identity
962  * @param d the daemon handle (pretty useless at this point, remove?)
963  * @param emsg non-null on failure
964  */
965 void
966 hostkey_callback (void *cls,
967                   const struct GNUNET_PeerIdentity *id,
968                   struct GNUNET_TESTING_Daemon *d, const char *emsg)
969 {
970   if (emsg != NULL)
971     {
972       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
973                   "Hostkey callback received error: %s\n", emsg);
974     }
975
976 #if VERBOSE > 1
977   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
978               "Hostkey (%d/%d) created for peer `%s'\n",
979               num_peers - peers_left, num_peers, GNUNET_i2s (id));
980 #endif
981
982 #if PROGRESS_BARS
983   if ((num_peers - peers_left) % modnum == 0)
984     {
985       if (num_peers - peers_left == 0)
986         fprintf (stdout, "0%%");
987       else
988         fprintf (stdout, "%d%%",
989                  (int) (((float) (num_peers - peers_left) /
990                          num_peers) * 100));
991
992     }
993   else if ((num_peers - peers_left) % dotnum == 0)
994     {
995       fprintf (stdout, ".");
996     }
997   fflush (stdout);
998 #endif
999   peers_left--;
1000   if (peers_left == 0)
1001     {
1002 #if PROGRESS_BARS
1003       fprintf (stdout, "100%%]\n");
1004       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1005                   "All %d hostkeys created, now creating topology!\n",
1006                   num_peers);
1007 #endif
1008       GNUNET_SCHEDULER_cancel (die_task);
1009       /* Set up task in case topology creation doesn't finish
1010        * within a reasonable amount of time */
1011       die_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT,
1012                                                &end_badly,
1013                                                "from create_topology");
1014       GNUNET_SCHEDULER_add_now (&create_topology, NULL);
1015       ok = 0;
1016     }
1017 }
1018
1019 static void
1020 run (void *cls,
1021      char *const *args,
1022      const char *cfgfile, const struct GNUNET_CONFIGURATION_Handle *cfg)
1023 {
1024   char *topology_str;
1025   char *connect_topology_str;
1026   char *blacklist_topology_str;
1027   char *connect_topology_option_str;
1028   char *connect_topology_option_modifier_string;
1029   unsigned long long temp_settle;
1030   ok = 1;
1031
1032   dotOutFile = fopen (dotOutFileName, "w");
1033   if (dotOutFile != NULL)
1034     {
1035       fprintf (dotOutFile, "strict graph G {\n");
1036     }
1037
1038 #if VERBOSE
1039   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1040               "Starting daemons based on config file %s\n", cfgfile);
1041 #endif
1042
1043   if (GNUNET_YES !=
1044       GNUNET_CONFIGURATION_get_value_string (cfg, "paths", "servicehome",
1045                                              &test_directory))
1046     {
1047       ok = 404;
1048       return;
1049     }
1050
1051   if ((GNUNET_YES ==
1052        GNUNET_CONFIGURATION_get_value_string (cfg, "testing", "topology",
1053                                               &topology_str))
1054       && (GNUNET_NO == GNUNET_TESTING_topology_get (&topology, topology_str)))
1055     {
1056       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1057                   "Invalid topology `%s' given for section %s option %s\n",
1058                   topology_str, "TESTING", "TOPOLOGY");
1059       topology = GNUNET_TESTING_TOPOLOGY_CLIQUE;        /* Defaults to NONE, so set better default here */
1060     }
1061
1062   if ((GNUNET_YES ==
1063        GNUNET_CONFIGURATION_get_value_string (cfg, "testing",
1064                                               "connect_topology",
1065                                               &connect_topology_str))
1066       && (GNUNET_NO ==
1067           GNUNET_TESTING_topology_get (&connection_topology,
1068                                        connect_topology_str)))
1069     {
1070       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1071                   "Invalid connect topology `%s' given for section %s option %s\n",
1072                   connect_topology_str, "TESTING", "CONNECT_TOPOLOGY");
1073     }
1074   GNUNET_free_non_null (connect_topology_str);
1075   if ((GNUNET_YES ==
1076        GNUNET_CONFIGURATION_get_value_string (cfg, "testing",
1077                                               "connect_topology_option",
1078                                               &connect_topology_option_str))
1079       && (GNUNET_NO ==
1080           GNUNET_TESTING_topology_option_get (&connect_topology_option,
1081                                               connect_topology_option_str)))
1082     {
1083       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1084                   "Invalid connect topology option `%s' given for section %s option %s\n",
1085                   connect_topology_option_str, "TESTING",
1086                   "CONNECT_TOPOLOGY_OPTION");
1087       connect_topology_option = GNUNET_TESTING_TOPOLOGY_OPTION_ALL;     /* Defaults to NONE, set to ALL */
1088     }
1089   GNUNET_free_non_null (connect_topology_option_str);
1090   if (GNUNET_YES ==
1091       GNUNET_CONFIGURATION_get_value_string (cfg, "testing",
1092                                              "connect_topology_option_modifier",
1093                                              &connect_topology_option_modifier_string))
1094     {
1095       if (sscanf
1096           (connect_topology_option_modifier_string, "%lf",
1097            &connect_topology_option_modifier) != 1)
1098         {
1099           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1100                       _
1101                       ("Invalid value `%s' for option `%s' in section `%s': expected float\n"),
1102                       connect_topology_option_modifier_string,
1103                       "connect_topology_option_modifier", "TESTING");
1104         }
1105       GNUNET_free (connect_topology_option_modifier_string);
1106     }
1107
1108   if (GNUNET_YES !=
1109       GNUNET_CONFIGURATION_get_value_string (cfg, "testing",
1110                                              "blacklist_transports",
1111                                              &blacklist_transports))
1112     blacklist_transports = NULL;
1113
1114   if ((GNUNET_YES ==
1115        GNUNET_CONFIGURATION_get_value_string (cfg, "testing",
1116                                               "blacklist_topology",
1117                                               &blacklist_topology_str))
1118       && (GNUNET_NO ==
1119           GNUNET_TESTING_topology_get (&blacklist_topology,
1120                                        blacklist_topology_str)))
1121     {
1122       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1123                   "Invalid topology `%s' given for section %s option %s\n",
1124                   topology_str, "TESTING", "BLACKLIST_TOPOLOGY");
1125     }
1126   GNUNET_free_non_null (topology_str);
1127   GNUNET_free_non_null (blacklist_topology_str);
1128
1129   if (GNUNET_OK ==
1130       GNUNET_CONFIGURATION_get_value_number (cfg, "testing", "settle_time",
1131                                              &temp_settle))
1132     settle_time =
1133       GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, temp_settle);
1134
1135   if (GNUNET_OK ==
1136       GNUNET_CONFIGURATION_get_value_number (cfg, "testing", "connect_timeout",
1137                                              &temp_settle))
1138     connect_timeout =
1139       GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, temp_settle);
1140   else
1141     {
1142       GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Must provide option %s:%s!\n", "testing", "connect_timeout");
1143       return;
1144     }
1145
1146
1147   if (GNUNET_OK !=
1148         GNUNET_CONFIGURATION_get_value_number (cfg, "testing", "connect_attempts",
1149                                                &connect_attempts))
1150     {
1151       GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Must provide option %s:%s!\n", "testing", "connect_attempts");
1152       return;
1153     }
1154
1155   if (GNUNET_SYSERR ==
1156       GNUNET_CONFIGURATION_get_value_number (cfg, "testing", "num_peers",
1157                                              &num_peers))
1158     num_peers = DEFAULT_NUM_PEERS;
1159
1160   main_cfg = cfg;
1161
1162   peers_left = num_peers;
1163   modnum = num_peers / 4;
1164   dotnum = (num_peers / 50) + 1;
1165   if (modnum == 0)
1166     modnum = 1;
1167   if (dotnum == 0)
1168     dotnum = 1;
1169 #if PROGRESS_BARS
1170   fprintf (stdout, "Hostkey generation progress: [");
1171 #endif
1172   /* Set up a task to end testing if peer start fails */
1173   die_task =
1174     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
1175                                   (GNUNET_TIME_UNIT_SECONDS,
1176                                    SECONDS_PER_PEER_START * num_peers),
1177                                   &end_badly,
1178                                   "didn't generate all hostkeys within a reasonable amount of time!!!");
1179
1180   GNUNET_assert (num_peers > 0 && num_peers < (unsigned int) -1);
1181   pg = GNUNET_TESTING_daemons_start (cfg,
1182                                      peers_left,
1183                                      peers_left / 2,
1184                                      peers_left,
1185                                      GNUNET_TIME_relative_multiply
1186                                      (GNUNET_TIME_UNIT_SECONDS,
1187                                       SECONDS_PER_PEER_START * num_peers),
1188                                      &hostkey_callback, NULL,
1189                                      &peers_started_callback, NULL,
1190                                      &topology_callback, NULL, NULL);
1191
1192 }
1193
1194 static int
1195 check ()
1196 {
1197   char *binary_name;
1198   char *config_file_name;
1199   GNUNET_asprintf (&binary_name, "test-testing-topology-%s", topology_string);
1200   GNUNET_asprintf (&config_file_name, "test_testing_data_topology_%s.conf",
1201                    topology_string);
1202   int ret;
1203   char *const argv[] = { binary_name,
1204     "-c",
1205     config_file_name,
1206 #if VERBOSE
1207     "-L", "DEBUG",
1208 #endif
1209     NULL
1210   };
1211   struct GNUNET_GETOPT_CommandLineOption options[] = {
1212     GNUNET_GETOPT_OPTION_END
1213   };
1214   ret = GNUNET_PROGRAM_run ((sizeof (argv) / sizeof (char *)) - 1,
1215                             argv, binary_name, "nohelp", options, &run, &ok);
1216   if (ret != GNUNET_OK)
1217     {
1218       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1219                   "`test-testing-topology-%s': Failed with error code %d\n",
1220                   topology_string, ret);
1221     }
1222   GNUNET_free (binary_name);
1223   GNUNET_free (config_file_name);
1224   return ok;
1225 }
1226
1227 int
1228 main (int argc, char *argv[])
1229 {
1230   int ret;
1231   char *binary_start_pos;
1232   char *our_binary_name;
1233
1234   binary_start_pos = strchr (argv[0], '/');
1235   GNUNET_assert (binary_start_pos != NULL);
1236   topology_string = strstr (binary_start_pos, "_topology");
1237   GNUNET_assert (topology_string != NULL);
1238   topology_string++;
1239   topology_string = strstr (topology_string, "_");
1240   GNUNET_assert (topology_string != NULL);
1241   topology_string++;
1242
1243   GNUNET_asprintf (&our_binary_name, "test-testing-topology_%s",
1244                    topology_string);
1245   GNUNET_asprintf (&dotOutFileName, "topology_%s.dot", topology_string);
1246
1247   GNUNET_log_setup (our_binary_name,
1248 #if VERBOSE
1249                     "DEBUG",
1250 #else
1251                     "WARNING",
1252 #endif
1253                     NULL);
1254   ret = check ();
1255
1256   /**
1257    * Need to remove base directory, subdirectories taken care
1258    * of by the testing framework.
1259    */
1260   if (GNUNET_DISK_directory_remove (test_directory) != GNUNET_OK)
1261     {
1262       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1263                   "Failed to remove testing directory %s\n", test_directory);
1264     }
1265   GNUNET_free (our_binary_name);
1266   return ret;
1267 }
1268
1269 /* end of test_testing_topology.c */