provide how many links succeeded and how many failed in test master callback
[oweals/gnunet.git] / src / testbed / testbed_api_testbed.c
1 /*
2   This file is part of GNUnet
3   (C) 2008--2012 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 /**
22  * @file testbed/testbed_api_testbed.c
23  * @brief high-level testbed management
24  * @author Christian Grothoff
25  * @author Sree Harsha Totakura
26  */
27
28 #include "platform.h"
29 #include "gnunet_util_lib.h"
30 #include "gnunet_testbed_service.h"
31 #include "testbed_api_peers.h"
32 #include "testbed_api_hosts.h"
33 #include "testbed_api_topology.h"
34
35 /**
36  * Generic loggins shorthand
37  */
38 #define LOG(kind,...)                                           \
39   GNUNET_log_from (kind, "testbed-api-testbed", __VA_ARGS__)
40
41 /**
42  * Debug logging shortcut
43  */
44 #define DEBUG(...)                              \
45   LOG (GNUNET_ERROR_TYPE_DEBUG, __VA_ARGS__)
46
47 /**
48  * The default setup timeout in seconds
49  */
50 #define DEFAULT_SETUP_TIMEOUT 300
51
52 /**
53  * DLL of operations
54  */
55 struct DLLOperation
56 {
57   /**
58    * The testbed operation handle
59    */
60   struct GNUNET_TESTBED_Operation *op;
61
62   /**
63    * Context information for GNUNET_TESTBED_run()
64    */
65   struct RunContext *rc;
66
67   /**
68    * Closure
69    */
70   void *cls;
71
72   /**
73    * The next pointer for DLL
74    */
75   struct DLLOperation *next;
76
77   /**
78    * The prev pointer for DLL
79    */
80   struct DLLOperation *prev;
81 };
82
83
84 /**
85  * States of RunContext
86  */
87 enum State
88 {
89   /**
90    * Initial state
91    */
92   RC_INIT = 0,
93
94   /**
95    * Controllers on given hosts started and linked
96    */
97   RC_LINKED,
98
99   /**
100    * Peers are created
101    */
102   RC_PEERS_CREATED,
103
104   /**
105    * The testbed run is ready and the master callback can be called now. At this
106    * time the peers are all started and if a topology is provided in the
107    * configuration the topology would have been attempted
108    */
109   RC_READY,
110
111   /* /\** */
112   /*  * Peers are stopped */
113   /*  *\/ */
114   /* RC_PEERS_STOPPED, */
115
116   /* /\** */
117   /*  * Peers are destroyed */
118   /*  *\/ */
119   /* RC_PEERS_DESTROYED */
120
121   /**
122    * All peers shutdown (stopped and destroyed)
123    */
124   RC_PEERS_SHUTDOWN
125 };
126
127
128 /**
129  * Testbed Run Handle
130  */
131 struct RunContext
132 {
133   /**
134    * The controller handle
135    */
136   struct GNUNET_TESTBED_Controller *c;
137
138   /**
139    * The configuration of the controller. This is based on the cfg given to the
140    * function GNUNET_TESTBED_run(). We also use this config as a template while
141    * for peers
142    */
143   struct GNUNET_CONFIGURATION_Handle *cfg;
144
145   /**
146    * Handle to the host on which the controller runs
147    */
148   struct GNUNET_TESTBED_Host *h;
149
150   /**
151    * The handle to the controller process
152    */
153   struct GNUNET_TESTBED_ControllerProc *cproc;
154
155   /**
156    * The callback to use as controller callback
157    */
158   GNUNET_TESTBED_ControllerCallback cc;
159
160   /**
161    * The pointer to the controller callback
162    */
163   void *cc_cls;
164
165   /**
166    * The trusted IP string
167    */
168   char *trusted_ip;
169
170   /**
171    * TestMaster callback to call when testbed initialization is done
172    */
173   GNUNET_TESTBED_TestMaster test_master;
174
175   /**
176    * The closure for the TestMaster callback
177    */
178   void *test_master_cls;
179
180   /**
181    * The head element of DLL operations
182    */
183   struct DLLOperation *dll_op_head;
184
185   /**
186    * The tail element of DLL operations
187    */
188   struct DLLOperation *dll_op_tail;
189
190   /**
191    * An array of hosts loaded from the hostkeys file
192    */
193   struct GNUNET_TESTBED_Host **hosts;
194
195   /**
196    * The handle for whether a host is habitable or not
197    */
198   struct GNUNET_TESTBED_HostHabitableCheckHandle **hc_handles;
199
200   /**
201    * Array of peers which we create
202    */
203   struct GNUNET_TESTBED_Peer **peers;
204
205   /**
206    * The topology generation operation. Will be null if no topology is set in
207    * the configuration
208    */
209   struct GNUNET_TESTBED_Operation *topology_operation;
210
211   /**
212    * The file containing topology data. Only used if the topology is set to 'FROM_FILE'
213    */
214   char *topo_file;
215
216   /**
217    * Host registration handle
218    */
219   struct GNUNET_TESTBED_HostRegistrationHandle *reg_handle;
220
221   /**
222    * Profiling start time
223    */
224   struct GNUNET_TIME_Absolute pstart_time;
225
226   /**
227    * Host registration task
228    */
229   GNUNET_SCHEDULER_TaskIdentifier register_hosts_task;
230
231   /**
232    * Task to be run while shutting down
233    */
234   GNUNET_SCHEDULER_TaskIdentifier shutdown_run_task;
235
236   /**
237    * Task to be run of a timeout
238    */
239   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
240
241   /**
242    * Task run upon shutdown interrupts
243    */
244   GNUNET_SCHEDULER_TaskIdentifier interrupt_task;
245
246   /**
247    * The event mask for the controller
248    */
249   uint64_t event_mask;
250
251   /**
252    * State of this context
253    */
254   enum State state;
255
256   /**
257    * The topology which has to be achieved with the peers started in this context
258    */
259   enum GNUNET_TESTBED_TopologyOption topology;
260
261   /**
262    * Have we already shutdown
263    */
264   int shutdown;
265
266   /**
267    * Number of hosts in the given host file
268    */
269   unsigned int num_hosts;
270
271   /**
272    * Number of registered hosts. Also used as a counter while checking
273    * habitabillity of hosts
274    */
275   unsigned int reg_hosts;
276
277   /**
278    * Current peer count for an operation; Set this to 0 and increment for each
279    * successful operation on a peer
280    */
281   unsigned int peer_count;
282
283   /**
284    * number of peers to start
285    */
286   unsigned int num_peers;
287
288   /**
289    * Expected overlay connects. Should be zero if no topology is relavant
290    */
291   unsigned int num_oc;
292
293   /**
294    * Number of random links to established
295    */
296   unsigned int random_links;
297
298   /**
299    * the number of overlay link connection attempts that succeeded
300    */
301   unsigned int links_succeeded;
302
303   /**
304    * the number of overlay link connection attempts that failed
305    */
306   unsigned int links_failed;
307
308 };
309
310
311 /**
312  * Assuming all peers have been destroyed cleanup run handle
313  *
314  * @param cls the run handle
315  * @param tc the task context from scheduler
316  */
317 static void
318 cleanup_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
319 {
320   struct RunContext *rc = cls;
321   unsigned int hid;
322
323   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == rc->register_hosts_task);
324   GNUNET_assert (NULL == rc->reg_handle);
325   GNUNET_assert (NULL == rc->peers);
326   GNUNET_assert (NULL == rc->hc_handles);
327   GNUNET_assert (RC_PEERS_SHUTDOWN == rc->state);
328   GNUNET_assert (NULL == rc->dll_op_head);
329   if (NULL != rc->c)
330     GNUNET_TESTBED_controller_disconnect (rc->c);
331   if (NULL != rc->cproc)
332     GNUNET_TESTBED_controller_stop (rc->cproc);
333   if (NULL != rc->h)
334     GNUNET_TESTBED_host_destroy (rc->h);
335   for (hid = 0; hid < rc->num_hosts; hid++)
336     GNUNET_TESTBED_host_destroy (rc->hosts[hid]);
337   GNUNET_free_non_null (rc->hosts);
338   if (NULL != rc->cfg)
339     GNUNET_CONFIGURATION_destroy (rc->cfg);
340   GNUNET_free_non_null (rc->topo_file);
341   GNUNET_free_non_null (rc->trusted_ip);
342   GNUNET_free (rc);
343 }
344
345 static void
346 cleanup (struct RunContext *rc)
347 {
348   struct DLLOperation *dll_op;
349   unsigned int nhost;
350
351   if (NULL != rc->hc_handles)
352   {
353     for (nhost = 0; nhost < rc->num_hosts; nhost++)
354       if (NULL != rc->hc_handles[nhost])
355         GNUNET_TESTBED_is_host_habitable_cancel (rc->hc_handles[nhost]);
356     GNUNET_free (rc->hc_handles);
357     rc->hc_handles = NULL;
358   }
359   /* Stop register hosts task if it is running */
360   if (GNUNET_SCHEDULER_NO_TASK != rc->register_hosts_task)
361   {
362     GNUNET_SCHEDULER_cancel (rc->register_hosts_task);
363     rc->register_hosts_task = GNUNET_SCHEDULER_NO_TASK;
364   }
365   if (GNUNET_SCHEDULER_NO_TASK != rc->timeout_task)
366   {
367     GNUNET_SCHEDULER_cancel (rc->timeout_task);
368     rc->timeout_task = GNUNET_SCHEDULER_NO_TASK;
369   }
370   if (GNUNET_SCHEDULER_NO_TASK != rc->interrupt_task)
371   {
372     GNUNET_SCHEDULER_cancel (rc->interrupt_task);
373     rc->interrupt_task = GNUNET_SCHEDULER_NO_TASK;
374   }
375   if (NULL != rc->reg_handle)
376   {
377     GNUNET_TESTBED_cancel_registration (rc->reg_handle);
378     rc->reg_handle = NULL;
379   }
380   if (NULL != rc->topology_operation)
381   {
382     GNUNET_TESTBED_operation_done (rc->topology_operation);
383     rc->topology_operation = NULL;
384   }
385   /* cancel any exiting operations */
386   while (NULL != (dll_op = rc->dll_op_head))
387   {
388     GNUNET_TESTBED_operation_done (dll_op->op);
389     GNUNET_CONTAINER_DLL_remove (rc->dll_op_head, rc->dll_op_tail, dll_op);
390     GNUNET_free (dll_op);
391   }
392 }
393
394
395 /**
396  * Stops the testbed run and releases any used resources
397  *
398  * @param cls the tesbed run handle
399  * @param tc the task context from scheduler
400  */
401 static void
402 shutdown_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
403 {
404   struct RunContext *rc = cls;
405   struct DLLOperation *dll_op;
406
407   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != rc->shutdown_run_task);
408   rc->shutdown_run_task = GNUNET_SCHEDULER_NO_TASK;
409   GNUNET_assert (GNUNET_NO == rc->shutdown);
410   rc->shutdown = GNUNET_YES;
411   cleanup (rc);
412   if (NULL != rc->c)
413   {
414     if (NULL != rc->peers)
415     {
416       dll_op = GNUNET_malloc (sizeof (struct DLLOperation));
417       dll_op->op = GNUNET_TESTBED_shutdown_peers (rc->c, dll_op, NULL, NULL);
418       GNUNET_assert (NULL != dll_op->op);
419       DEBUG ("Shutting down peers\n");
420       rc->pstart_time = GNUNET_TIME_absolute_get ();
421       GNUNET_CONTAINER_DLL_insert_tail (rc->dll_op_head, rc->dll_op_tail,
422                                         dll_op);
423       return;
424     }
425   }
426   rc->state = RC_PEERS_SHUTDOWN;       /* No peers are present so we consider the
427                                         * state where all peers are SHUTDOWN  */
428   GNUNET_SCHEDULER_add_now (&cleanup_task, rc);
429 }
430
431
432 /**
433  * Function to shutdown now
434  *
435  * @param rc the RunContext
436  */
437 static void
438 shutdown_now (struct RunContext *rc)
439 {
440   if (GNUNET_YES == rc->shutdown)
441     return;
442   if (GNUNET_SCHEDULER_NO_TASK != rc->shutdown_run_task)
443     GNUNET_SCHEDULER_cancel (rc->shutdown_run_task);
444   GNUNET_SCHEDULER_shutdown (); /* Trigger shutdown in programs using this API */
445   rc->shutdown_run_task = GNUNET_SCHEDULER_add_now (&shutdown_run, rc);
446 }
447
448
449 static void
450 interrupt (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
451 {
452   struct RunContext *rc = cls;
453
454   rc->interrupt_task = GNUNET_SCHEDULER_NO_TASK;
455   shutdown_now (rc);
456 }
457
458
459 /**
460  * Function to return the string representation of the duration between current
461  * time and `pstart_time' in `RunContext'
462  *
463  * @param rc the RunContext
464  * @return the representation string; this is NOT reentrant
465  */
466 static const char *
467 prof_time (struct RunContext *rc)
468 {
469   struct GNUNET_TIME_Relative ptime;
470
471   ptime = GNUNET_TIME_absolute_get_duration (rc->pstart_time);
472   return GNUNET_STRINGS_relative_time_to_string (ptime, GNUNET_YES);
473 }
474
475
476 /**
477  * Task for starting peers
478  *
479  * @param cls the RunHandle
480  * @param tc the task context from scheduler
481  */
482 static void
483 start_peers_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
484 {
485   struct RunContext *rc = cls;
486   struct DLLOperation *dll_op;
487   unsigned int peer;
488
489   DEBUG ("Starting Peers\n");
490   rc->pstart_time = GNUNET_TIME_absolute_get ();
491   for (peer = 0; peer < rc->num_peers; peer++)
492   {
493     dll_op = GNUNET_malloc (sizeof (struct DLLOperation));
494     dll_op->op = GNUNET_TESTBED_peer_start (NULL, rc->peers[peer], NULL, NULL);
495     GNUNET_assert (NULL != dll_op->op);
496     dll_op->cls = rc->peers[peer];
497     GNUNET_CONTAINER_DLL_insert_tail (rc->dll_op_head, rc->dll_op_tail, dll_op);
498   }
499   rc->peer_count = 0;
500 }
501
502
503 /**
504  * Functions of this signature are called when a peer has been successfully
505  * created
506  *
507  * @param cls the closure from GNUNET_TESTBED_peer_create()
508  * @param peer the handle for the created peer; NULL on any error during
509  *          creation
510  * @param emsg NULL if peer is not NULL; else MAY contain the error description
511  */
512 static void
513 peer_create_cb (void *cls, struct GNUNET_TESTBED_Peer *peer, const char *emsg)
514 {
515   struct DLLOperation *dll_op = cls;
516   struct RunContext *rc;
517
518   GNUNET_assert (NULL != dll_op);
519   rc = dll_op->rc;
520   GNUNET_assert (NULL != rc);
521   GNUNET_CONTAINER_DLL_remove (rc->dll_op_head, rc->dll_op_tail, dll_op);
522   GNUNET_TESTBED_operation_done (dll_op->op);
523   GNUNET_free (dll_op);
524   if (NULL == peer)
525   {
526     if (NULL != emsg)
527       LOG (GNUNET_ERROR_TYPE_ERROR, "Error while creating a peer: %s\n",
528            emsg);
529     shutdown_now (rc);
530     return;
531   }
532   rc->peers[rc->peer_count] = peer;
533   rc->peer_count++;
534   if (rc->peer_count < rc->num_peers)
535     return;
536   DEBUG ("%u peers created in %s\n", rc->num_peers, prof_time (rc));
537   rc->state = RC_PEERS_CREATED;
538   GNUNET_SCHEDULER_add_now (&start_peers_task, rc);
539 }
540
541
542 /**
543  * call test master callback
544  *
545  * @param rc the RunContext
546  */
547 static void
548 call_master (struct RunContext *rc)
549 {
550   GNUNET_SCHEDULER_cancel (rc->timeout_task);
551   rc->timeout_task = GNUNET_SCHEDULER_NO_TASK;
552   if (NULL != rc->test_master)
553     rc->test_master (rc->test_master_cls, rc->num_peers, rc->peers,
554                      rc->links_succeeded, rc->links_failed);
555 }
556
557
558 /**
559  * Callbacks of this type are called when topology configuration is completed
560  *
561  * @param cls the operation closure given to
562  *          GNUNET_TESTBED_overlay_configure_topology_va() and
563  *          GNUNET_TESTBED_overlay_configure() calls
564  * @param nsuccess the number of successful overlay connects
565  * @param nfailures the number of overlay connects which failed
566  */
567 static void
568 topology_completion_callback (void *cls, unsigned int nsuccess,
569                               unsigned int nfailures)
570 {
571   struct RunContext *rc = cls;
572
573   DEBUG ("Overlay topology generated in %s\n", prof_time (rc));
574   GNUNET_TESTBED_operation_done (rc->topology_operation);
575   rc->topology_operation = NULL;
576   rc->links_succeeded = nsuccess;
577   rc->links_failed = nfailures;
578   rc->state = RC_READY;
579   call_master (rc);
580 }
581
582
583 /**
584  * Function to create peers
585  *
586  * @param rc the RunContext
587  */
588 static void
589 create_peers (struct RunContext *rc)
590 {
591   struct DLLOperation *dll_op;
592   unsigned int peer;
593
594   DEBUG ("Creating peers\n");
595   rc->pstart_time = GNUNET_TIME_absolute_get ();
596   rc->peers =
597       GNUNET_malloc (sizeof (struct GNUNET_TESTBED_Peer *) * rc->num_peers);
598   GNUNET_assert (NULL != rc->c);
599   rc->peer_count = 0;
600   for (peer = 0; peer < rc->num_peers; peer++)
601   {
602     dll_op = GNUNET_malloc (sizeof (struct DLLOperation));
603     dll_op->rc = rc;
604     dll_op->op =
605         GNUNET_TESTBED_peer_create (rc->c,
606                                     (0 ==
607                                      rc->num_hosts) ? rc->h : rc->hosts[peer %
608                                                                         rc->num_hosts],
609                                     rc->cfg, peer_create_cb, dll_op);    
610     GNUNET_assert (NULL != dll_op->op);
611     GNUNET_CONTAINER_DLL_insert_tail (rc->dll_op_head, rc->dll_op_tail, dll_op);
612   }
613 }
614
615
616 /**
617  * Signature of the event handler function called by the
618  * respective event controller.
619  *
620  * @param cls closure
621  * @param event information about the event
622  */
623 static void
624 event_cb (void *cls, const struct GNUNET_TESTBED_EventInformation *event)
625 {
626   struct RunContext *rc = cls;
627   struct DLLOperation *dll_op;
628
629   if (RC_INIT == rc->state)
630   {
631     switch (event->type)
632     {
633     case GNUNET_TESTBED_ET_OPERATION_FINISHED:
634       dll_op = event->op_cls;
635       if (NULL != event->details.operation_finished.emsg)
636       {
637         LOG (GNUNET_ERROR_TYPE_ERROR, _("Linking controllers failed. Exiting"));
638         shutdown_now (rc);
639       }
640       else
641         rc->reg_hosts++;
642       GNUNET_assert (event->op == dll_op->op);
643       GNUNET_CONTAINER_DLL_remove (rc->dll_op_head, rc->dll_op_tail, dll_op);
644       GNUNET_TESTBED_operation_done (dll_op->op);
645       GNUNET_free (dll_op);
646       if (rc->reg_hosts == rc->num_hosts)
647       {
648         rc->state = RC_LINKED;
649         create_peers (rc);
650       }
651       return;
652     default:
653       GNUNET_break (0);
654       shutdown_now (rc);
655       return;
656     }
657   }
658   for (dll_op = rc->dll_op_head; NULL != dll_op; dll_op = dll_op->next)
659   {
660     if ((GNUNET_TESTBED_ET_OPERATION_FINISHED == event->type) &&
661         (event->op == dll_op->op))
662       break;
663   }
664   if (NULL == dll_op)
665     goto call_cc;
666   GNUNET_CONTAINER_DLL_remove (rc->dll_op_head, rc->dll_op_tail, dll_op);
667   GNUNET_TESTBED_operation_done (dll_op->op);
668   GNUNET_free (dll_op);
669   if ( (GNUNET_NO == rc->shutdown)
670        && (NULL != event->details.operation_finished.emsg) )
671   {
672     LOG (GNUNET_ERROR_TYPE_ERROR, "A operation has failed with error: %s\n",
673          event->details.operation_finished.emsg);
674     shutdown_now (rc);
675     return;
676   }
677   GNUNET_assert (GNUNET_YES == rc->shutdown);
678   switch (rc->state)
679   {
680   case RC_LINKED:
681   case RC_PEERS_CREATED:
682   case RC_READY:
683     rc->state = RC_PEERS_SHUTDOWN;
684     GNUNET_free_non_null (rc->peers);
685     rc->peers = NULL;
686     DEBUG ("Peers shut down in %s\n", prof_time (rc));
687     GNUNET_SCHEDULER_add_now (&cleanup_task, rc);
688     break;
689   default:
690     GNUNET_assert (0);
691   }
692   return;
693
694 call_cc:
695   if ((0 != (rc->event_mask & (1LL << event->type))) && (NULL != rc->cc))
696     rc->cc (rc->cc_cls, event);
697   if (GNUNET_TESTBED_ET_PEER_START != event->type)
698     return;
699   for (dll_op = rc->dll_op_head; NULL != dll_op; dll_op = dll_op->next)
700     if ((NULL != dll_op->cls) &&
701         (event->details.peer_start.peer == dll_op->cls))
702       break;
703   if (NULL == dll_op)           /* Not our operation */
704     return;
705   GNUNET_CONTAINER_DLL_remove (rc->dll_op_head, rc->dll_op_tail, dll_op);
706   GNUNET_TESTBED_operation_done (dll_op->op);
707   GNUNET_free (dll_op);
708   rc->peer_count++;
709   if (rc->peer_count < rc->num_peers)
710     return;
711   DEBUG ("%u peers started in %s\n", rc->num_peers, prof_time (rc));
712   if (GNUNET_TESTBED_TOPOLOGY_NONE != rc->topology)
713   {
714     if ((GNUNET_TESTBED_TOPOLOGY_ERDOS_RENYI == rc->topology) ||
715         (GNUNET_TESTBED_TOPOLOGY_SMALL_WORLD_RING == rc->topology) ||
716         (GNUNET_TESTBED_TOPOLOGY_SMALL_WORLD == rc->topology))
717     {
718       rc->topology_operation =
719           GNUNET_TESTBED_overlay_configure_topology (NULL, rc->num_peers,
720                                                      rc->peers, &rc->num_oc,
721                                                      &topology_completion_callback,
722                                                      rc,
723                                                      rc->topology,
724                                                      rc->random_links,
725                                                      GNUNET_TESTBED_TOPOLOGY_OPTION_END);
726     }
727     else if (GNUNET_TESTBED_TOPOLOGY_FROM_FILE == rc->topology)
728     {
729       GNUNET_assert (NULL != rc->topo_file);
730       rc->topology_operation =
731           GNUNET_TESTBED_overlay_configure_topology (NULL, rc->num_peers,
732                                                      rc->peers, &rc->num_oc,
733                                                      &topology_completion_callback,
734                                                      rc,
735                                                      rc->topology,
736                                                      rc->topo_file,
737                                                      GNUNET_TESTBED_TOPOLOGY_OPTION_END);
738     }
739     else
740       rc->topology_operation =
741           GNUNET_TESTBED_overlay_configure_topology (NULL, rc->num_peers,
742                                                      rc->peers, &rc->num_oc,
743                                                      &topology_completion_callback,
744                                                      rc,
745                                                      rc->topology,
746                                                      GNUNET_TESTBED_TOPOLOGY_OPTION_END);
747     if (NULL == rc->topology_operation)
748       LOG (GNUNET_ERROR_TYPE_WARNING,
749            "Not generating topology. Check number of peers\n");
750     else
751     {
752       DEBUG ("Creating overlay topology\n");
753       rc->pstart_time = GNUNET_TIME_absolute_get ();
754       return;
755     }
756   }
757   rc->state = RC_READY;
758   call_master (rc);
759 }
760
761
762 /**
763  * Task to register all hosts available in the global host list
764  *
765  * @param cls the RunContext
766  * @param tc the scheduler task context
767  */
768 static void
769 register_hosts (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
770
771
772 /**
773  * Callback which will be called to after a host registration succeeded or failed
774  *
775  * @param cls the closure
776  * @param emsg the error message; NULL if host registration is successful
777  */
778 static void
779 host_registration_completion (void *cls, const char *emsg)
780 {
781   struct RunContext *rc = cls;
782
783   rc->reg_handle = NULL;
784   if (NULL != emsg)
785   {
786     LOG (GNUNET_ERROR_TYPE_WARNING,
787          _("Host registration failed for a host. Error: %s\n"), emsg);
788     shutdown_now (rc);
789     return;
790   }
791   rc->register_hosts_task = GNUNET_SCHEDULER_add_now (&register_hosts, rc);
792 }
793
794
795 /**
796  * Task to register all hosts available in the global host list
797  *
798  * @param cls RunContext
799  * @param tc the scheduler task context
800  */
801 static void
802 register_hosts (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
803 {
804   struct RunContext *rc = cls;
805   struct DLLOperation *dll_op;
806   unsigned int slave;
807
808   rc->register_hosts_task = GNUNET_SCHEDULER_NO_TASK;
809   if (rc->reg_hosts == rc->num_hosts)
810   {
811     DEBUG ("All hosts successfully registered\n");
812     /* Start slaves */
813     for (slave = 0; slave < rc->num_hosts; slave++)
814     {
815       dll_op = GNUNET_malloc (sizeof (struct DLLOperation));
816       dll_op->rc = rc;
817       dll_op->op =
818           GNUNET_TESTBED_controller_link (dll_op, rc->c, rc->hosts[slave],
819                                           rc->h, rc->cfg, GNUNET_YES);
820       GNUNET_assert (NULL != dll_op->op);
821       GNUNET_CONTAINER_DLL_insert_tail (rc->dll_op_head, rc->dll_op_tail,
822                                         dll_op);
823     }
824     rc->reg_hosts = 0;
825     return;
826   }
827   rc->reg_handle =
828       GNUNET_TESTBED_register_host (rc->c, rc->hosts[rc->reg_hosts],
829                                     host_registration_completion, rc);
830   rc->reg_hosts++;
831 }
832
833
834 /**
835  * Callback to signal successfull startup of the controller process
836  *
837  * @param cls the closure from GNUNET_TESTBED_controller_start()
838  * @param cfg the configuration with which the controller has been started;
839  *          NULL if status is not GNUNET_OK
840  * @param status GNUNET_OK if the startup is successfull; GNUNET_SYSERR if not,
841  *          GNUNET_TESTBED_controller_stop() shouldn't be called in this case
842  */
843 static void
844 controller_status_cb (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg,
845                       int status)
846 {
847   struct RunContext *rc = cls;
848   uint64_t event_mask;
849
850   if (status != GNUNET_OK)
851   {
852     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
853                 _("Controller crash detected. Shutting down.\n"));
854     rc->cproc = NULL;
855     cleanup (rc);
856     if (NULL != rc->peers)
857     {
858       GNUNET_free (rc->peers);
859       rc->peers = NULL;
860     }
861     if (GNUNET_YES == rc->shutdown)
862     {
863       rc->state = RC_PEERS_SHUTDOWN;
864       GNUNET_SCHEDULER_add_now (&cleanup_task, rc);
865     }
866     else
867       shutdown_now (rc);
868     return;
869   }
870   GNUNET_CONFIGURATION_destroy (rc->cfg);
871   rc->cfg = GNUNET_CONFIGURATION_dup (cfg);
872   event_mask = rc->event_mask;
873   event_mask |= (1LL << GNUNET_TESTBED_ET_OPERATION_FINISHED);
874   event_mask |= (1LL << GNUNET_TESTBED_ET_PEER_START);
875   if (rc->topology < GNUNET_TESTBED_TOPOLOGY_NONE)
876     event_mask |= GNUNET_TESTBED_ET_CONNECT;
877   rc->c =
878       GNUNET_TESTBED_controller_connect (rc->cfg, rc->h, event_mask, &event_cb,
879                                          rc);
880   if (0 < rc->num_hosts)
881   {
882     rc->reg_hosts = 0;
883     rc->register_hosts_task = GNUNET_SCHEDULER_add_now (&register_hosts, rc);
884     return;
885   }
886   rc->state = RC_LINKED;
887   create_peers (rc);
888 }
889
890
891 /**
892  * Callback function invoked for each interface found.
893  *
894  * @param cls closure
895  * @param name name of the interface (can be NULL for unknown)
896  * @param isDefault is this presumably the default interface
897  * @param addr address of this interface (can be NULL for unknown or unassigned)
898  * @param broadcast_addr the broadcast address (can be NULL for unknown or unassigned)
899  * @param netmask the network mask (can be NULL for unknown or unassigned))
900  * @param addrlen length of the address
901  * @return GNUNET_OK to continue iteration, GNUNET_SYSERR to abort
902  */
903 static int
904 netint_proc (void *cls, const char *name, int isDefault,
905              const struct sockaddr *addr, const struct sockaddr *broadcast_addr,
906              const struct sockaddr *netmask, socklen_t addrlen)
907 {
908   struct RunContext *rc = cls;
909   char hostip[NI_MAXHOST];
910   char *buf;
911
912   if (sizeof (struct sockaddr_in) != addrlen)
913     return GNUNET_OK;           /* Only consider IPv4 for now */
914   if (0 !=
915       getnameinfo (addr, addrlen, hostip, NI_MAXHOST, NULL, 0, NI_NUMERICHOST))
916     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "getnameinfo");
917   if (NULL == rc->trusted_ip)
918   {
919     rc->trusted_ip = GNUNET_strdup (hostip);
920     return GNUNET_YES;
921   }
922   (void) GNUNET_asprintf (&buf, "%s; %s", rc->trusted_ip, hostip);
923   GNUNET_free (rc->trusted_ip);
924   rc->trusted_ip = buf;
925   return GNUNET_YES;
926 }
927
928
929 /**
930  * Callbacks of this type are called by GNUNET_TESTBED_is_host_habitable to
931  * inform whether the given host is habitable or not. The Handle returned by
932  * GNUNET_TESTBED_is_host_habitable() is invalid after this callback is called
933  *
934  * @param cls NULL
935  * @param host the host whose status is being reported; will be NULL if the host
936  *          given to GNUNET_TESTBED_is_host_habitable() is NULL
937  * @param status GNUNET_YES if it is habitable; GNUNET_NO if not
938  */
939 static void
940 host_habitable_cb (void *cls, const struct GNUNET_TESTBED_Host *host,
941                    int status)
942 {
943   struct RunContext *rc = cls;
944   struct GNUNET_TESTBED_Host **old_hosts;
945   unsigned int nhost;
946
947   for (nhost = 0; nhost < rc->num_hosts; nhost++)
948   {
949     if (host == rc->hosts[nhost])
950       break;
951   }
952   GNUNET_assert (nhost != rc->num_hosts);
953   rc->hc_handles[nhost] = NULL;
954   if (GNUNET_NO == status)
955   {
956     if ((NULL != host) && (NULL != GNUNET_TESTBED_host_get_hostname (host)))
957       LOG (GNUNET_ERROR_TYPE_ERROR, _("Host %s cannot start testbed\n"),
958            GNUNET_TESTBED_host_get_hostname (host));
959     else
960       LOG (GNUNET_ERROR_TYPE_ERROR,
961            _("Testbed cannot be started on localhost\n"));
962     shutdown_now (rc);
963     return;
964   }
965   rc->reg_hosts++;
966   if (rc->reg_hosts < rc->num_hosts)
967     return;
968   GNUNET_free (rc->hc_handles);
969   rc->hc_handles = NULL;
970   rc->h = rc->hosts[0];
971   rc->num_hosts--;
972   if (0 < rc->num_hosts)
973   {
974     old_hosts = rc->hosts;
975     rc->hosts =
976         GNUNET_malloc (sizeof (struct GNUNET_TESTBED_Host *) * rc->num_hosts);
977     memcpy (rc->hosts, &old_hosts[1],
978             (sizeof (struct GNUNET_TESTBED_Host *) * rc->num_hosts));
979     GNUNET_free (old_hosts);
980   }
981   else
982   {
983     GNUNET_free (rc->hosts);
984     rc->hosts = NULL;
985   }
986   GNUNET_OS_network_interfaces_list (netint_proc, rc);
987   if (NULL == rc->trusted_ip)
988     rc->trusted_ip = GNUNET_strdup ("127.0.0.1");
989   rc->cproc =
990       GNUNET_TESTBED_controller_start (rc->trusted_ip, rc->h, rc->cfg,
991                                        &controller_status_cb, rc);
992   GNUNET_free (rc->trusted_ip);
993   rc->trusted_ip = NULL;
994   if (NULL == rc->cproc)
995   {
996     LOG (GNUNET_ERROR_TYPE_ERROR, _("Cannot start the master controller"));
997     shutdown_now (rc);
998   }
999 }
1000
1001
1002 /**
1003  * Task run upon timeout while setting up the testbed
1004  *
1005  * @param cls the RunContext
1006  * @param tc the task context
1007  */
1008 static void
1009 timeout_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1010 {
1011   struct RunContext *rc = cls;
1012   
1013   rc->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1014   LOG (GNUNET_ERROR_TYPE_ERROR, _("Shutting down testbed due to timeout while setup.\n"));
1015   shutdown_now (rc);
1016    if (NULL != rc->test_master)
1017      rc->test_master (rc->test_master_cls, 0, NULL, 0, 0);
1018    rc->test_master = NULL;
1019 }
1020
1021
1022 /**
1023  * Convenience method for running a testbed with
1024  * a single call.  Underlay and overlay topology
1025  * are configured using the "UNDERLAY" and "OVERLAY"
1026  * options in the "[testbed]" section of the configuration\
1027  * (with possible options given in "UNDERLAY_XXX" and/or
1028  * "OVERLAY_XXX").
1029  *
1030  * The testbed is to be terminated using a call to
1031  * "GNUNET_SCHEDULER_shutdown".
1032  *
1033  * @param host_filename name of the file with the 'hosts', NULL
1034  *        to run everything on 'localhost'
1035  * @param cfg configuration to use (for testbed, controller and peers)
1036  * @param num_peers number of peers to start; FIXME: maybe put that ALSO into cfg?
1037  * @param event_mask bit mask with set of events to call 'cc' for;
1038  *                   or-ed values of "1LL" shifted by the
1039  *                   respective 'enum GNUNET_TESTBED_EventType'
1040  *                   (i.e.  "(1LL << GNUNET_TESTBED_ET_CONNECT) || ...")
1041  * @param cc controller callback to invoke on events; This callback is called
1042  *          for all peer start events even if GNUNET_TESTBED_ET_PEER_START isn't
1043  *          set in the event_mask as this is the only way get access to the
1044  *          handle of each peer
1045  * @param cc_cls closure for cc
1046  * @param test_master this callback will be called once the test is ready
1047  * @param test_master_cls closure for 'test_master'.
1048  */
1049 void
1050 GNUNET_TESTBED_run (const char *host_filename,
1051                     const struct GNUNET_CONFIGURATION_Handle *cfg,
1052                     unsigned int num_peers, uint64_t event_mask,
1053                     GNUNET_TESTBED_ControllerCallback cc, void *cc_cls,
1054                     GNUNET_TESTBED_TestMaster test_master,
1055                     void *test_master_cls)
1056 {
1057   struct RunContext *rc;
1058   char *topology;
1059   struct GNUNET_TIME_Relative timeout;
1060   unsigned long long random_links;
1061   unsigned int hid;
1062   unsigned int nhost;
1063
1064   GNUNET_assert (num_peers > 0);
1065   rc = GNUNET_malloc (sizeof (struct RunContext));
1066   rc->cfg = GNUNET_CONFIGURATION_dup (cfg);
1067 #if ENABLE_LL
1068   rc->num_hosts = GNUNET_TESTBED_hosts_load_from_loadleveler (rc->cfg,
1069                                                               &rc->hosts);
1070   if (0 == rc->num_hosts)
1071   {
1072     LOG (GNUNET_ERROR_TYPE_WARNING,
1073            _("No hosts loaded from LoadLeveler. Need at least one host\n"));
1074     goto error_cleanup;
1075   }
1076 #else
1077   if (NULL != host_filename)
1078   {
1079     rc->num_hosts =
1080         GNUNET_TESTBED_hosts_load_from_file (host_filename, rc->cfg,
1081                                              &rc->hosts);
1082     if (0 == rc->num_hosts)
1083     {
1084       LOG (GNUNET_ERROR_TYPE_WARNING,
1085            _("No hosts loaded. Need at least one host\n"));
1086       goto error_cleanup;
1087     }
1088   }
1089   else
1090     rc->h = GNUNET_TESTBED_host_create (NULL, NULL, rc->cfg, 0);
1091 #endif
1092   rc->num_peers = num_peers;
1093   rc->event_mask = event_mask;
1094   rc->cc = cc;
1095   rc->cc_cls = cc_cls;
1096   rc->test_master = test_master;
1097   rc->test_master_cls = test_master_cls;
1098   rc->state = RC_INIT;
1099   rc->topology = GNUNET_TESTBED_TOPOLOGY_NONE;
1100   if (GNUNET_OK ==
1101       GNUNET_CONFIGURATION_get_value_string (rc->cfg, "testbed",
1102                                              "OVERLAY_TOPOLOGY", &topology))
1103   {
1104     if (GNUNET_NO == GNUNET_TESTBED_topology_get_ (&rc->topology, topology))
1105     {
1106       GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR, "testbed",
1107                                  "OVERLAY_TOPLOGY",
1108                                  _
1109                                  ("Specified topology must be supported by testbed"));
1110     }
1111     GNUNET_free (topology);
1112   }
1113   switch (rc->topology)
1114   {
1115   case GNUNET_TESTBED_TOPOLOGY_ERDOS_RENYI:
1116   case GNUNET_TESTBED_TOPOLOGY_SMALL_WORLD_RING:
1117   case GNUNET_TESTBED_TOPOLOGY_SMALL_WORLD:
1118     if (GNUNET_OK !=
1119         GNUNET_CONFIGURATION_get_value_number (rc->cfg, "testbed",
1120                                                "OVERLAY_RANDOM_LINKS",
1121                                                &random_links))
1122     {
1123       /* OVERLAY option RANDOM & SMALL_WORLD_RING requires OVERLAY_RANDOM_LINKS
1124        * option to be set to the number of random links to be established  */
1125       GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, "testbed",
1126                                  "OVERLAY_RANDOM_LINKS");
1127       goto error_cleanup;
1128     }
1129     if (random_links > UINT32_MAX)
1130     {
1131       GNUNET_break (0);         /* Too big number */
1132       goto error_cleanup;
1133     }
1134     rc->random_links = (unsigned int) random_links;
1135     break;
1136   case GNUNET_TESTBED_TOPOLOGY_FROM_FILE:
1137     if (GNUNET_OK !=
1138         GNUNET_CONFIGURATION_get_value_string (rc->cfg, "testbed",
1139                                                "OVERLAY_TOPOLOGY_FILE",
1140                                                &rc->topo_file))
1141     {
1142       GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, "testbed",
1143                                  "OVERLAY_TOPOLOGY_FILE");
1144       goto error_cleanup;
1145     }
1146   default:
1147     /* Warn if OVERLAY_RANDOM_LINKS is present that it will be ignored */
1148     if (GNUNET_YES ==
1149         GNUNET_CONFIGURATION_have_value (rc->cfg, "testbed",
1150                                          "OVERLAY_RANDOM_LINKS"))
1151       LOG (GNUNET_ERROR_TYPE_WARNING,
1152            "Ignoring value of `OVERLAY_RANDOM_LINKS' in given configuration\n");
1153     break;
1154   }
1155   if (0 != rc->num_hosts)
1156   {
1157     rc->hc_handles =
1158         GNUNET_malloc (sizeof (struct GNUNET_TESTBED_HostHabitableCheckHandle *)
1159                        * rc->num_hosts);
1160     for (nhost = 0; nhost < rc->num_hosts; nhost++)
1161     {
1162       if (NULL ==
1163           (rc->hc_handles[nhost] =
1164            GNUNET_TESTBED_is_host_habitable (rc->hosts[nhost], rc->cfg,
1165                                              &host_habitable_cb, rc)))
1166       {
1167         GNUNET_break (0);
1168         for (nhost = 0; nhost < rc->num_hosts; nhost++)
1169           if (NULL != rc->hc_handles[nhost])
1170             GNUNET_TESTBED_is_host_habitable_cancel (rc->hc_handles[nhost]);
1171         GNUNET_free (rc->hc_handles);
1172         rc->hc_handles = NULL;
1173         goto error_cleanup;
1174       }
1175     }
1176   }
1177   else
1178     rc->cproc =
1179         GNUNET_TESTBED_controller_start ("127.0.0.1", rc->h, rc->cfg,
1180                                          &controller_status_cb, rc);
1181   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_time (cfg, "TESTBED",
1182                                                         "SETUP_TIMEOUT",
1183                                                         &timeout))
1184   {
1185     timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
1186                                              DEFAULT_SETUP_TIMEOUT);
1187   }
1188   rc->timeout_task =
1189       GNUNET_SCHEDULER_add_delayed (timeout, &timeout_task, rc);
1190   rc->interrupt_task =
1191       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &interrupt,
1192                                     rc);
1193   return;
1194
1195 error_cleanup:
1196   if (NULL != rc->h)
1197     GNUNET_TESTBED_host_destroy (rc->h);
1198   if (NULL != rc->hosts)
1199   {
1200     for (hid = 0; hid < rc->num_hosts; hid++)
1201       if (NULL != rc->hosts[hid])
1202         GNUNET_TESTBED_host_destroy (rc->hosts[hid]);
1203     GNUNET_free (rc->hosts);
1204   }
1205   if (NULL != rc->cfg)
1206     GNUNET_CONFIGURATION_destroy (rc->cfg);
1207   GNUNET_free (rc);
1208 }
1209
1210
1211 /* end of testbed_api_testbed.c */