- exit when an operation fails
[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    * The event mask for the controller
243    */
244   uint64_t event_mask;
245
246   /**
247    * State of this context
248    */
249   enum State state;
250
251   /**
252    * The topology which has to be achieved with the peers started in this context
253    */
254   enum GNUNET_TESTBED_TopologyOption topology;
255
256   /**
257    * Have we already shutdown
258    */
259   int shutdown;
260
261   /**
262    * Number of hosts in the given host file
263    */
264   unsigned int num_hosts;
265
266   /**
267    * Number of registered hosts. Also used as a counter while checking
268    * habitabillity of hosts
269    */
270   unsigned int reg_hosts;
271
272   /**
273    * Current peer count for an operation; Set this to 0 and increment for each
274    * successful operation on a peer
275    */
276   unsigned int peer_count;
277
278   /**
279    * number of peers to start
280    */
281   unsigned int num_peers;
282
283   /**
284    * Expected overlay connects. Should be zero if no topology is relavant
285    */
286   unsigned int num_oc;
287
288   /**
289    * Number of random links to established
290    */
291   unsigned int random_links;
292
293 };
294
295
296 /**
297  * Assuming all peers have been destroyed cleanup run handle
298  *
299  * @param cls the run handle
300  * @param tc the task context from scheduler
301  */
302 static void
303 cleanup_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
304 {
305   struct RunContext *rc = cls;
306   unsigned int hid;
307
308   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == rc->register_hosts_task);
309   GNUNET_assert (NULL == rc->reg_handle);
310   GNUNET_assert (NULL == rc->peers);
311   GNUNET_assert (NULL == rc->hc_handles);
312   GNUNET_assert (RC_PEERS_SHUTDOWN == rc->state);
313   GNUNET_assert (NULL == rc->dll_op_head);
314   if (NULL != rc->c)
315     GNUNET_TESTBED_controller_disconnect (rc->c);
316   if (NULL != rc->cproc)
317     GNUNET_TESTBED_controller_stop (rc->cproc);
318   if (NULL != rc->h)
319     GNUNET_TESTBED_host_destroy (rc->h);
320   for (hid = 0; hid < rc->num_hosts; hid++)
321     GNUNET_TESTBED_host_destroy (rc->hosts[hid]);
322   GNUNET_free_non_null (rc->hosts);
323   if (NULL != rc->cfg)
324     GNUNET_CONFIGURATION_destroy (rc->cfg);
325   GNUNET_free_non_null (rc->topo_file);
326   GNUNET_free_non_null (rc->trusted_ip);
327   GNUNET_free (rc);
328 }
329
330
331 /**
332  * Stops the testbed run and releases any used resources
333  *
334  * @param cls the tesbed run handle
335  * @param tc the task context from scheduler
336  */
337 static void
338 shutdown_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
339 {
340   struct RunContext *rc = cls;
341   struct DLLOperation *dll_op;
342   unsigned int nhost;
343
344   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != rc->shutdown_run_task);
345   rc->shutdown_run_task = GNUNET_SCHEDULER_NO_TASK;
346   GNUNET_assert (GNUNET_NO == rc->shutdown);
347   rc->shutdown = GNUNET_YES;
348   if (NULL != rc->hc_handles)
349   {
350     for (nhost = 0; nhost < rc->num_hosts; nhost++)
351       if (NULL != rc->hc_handles[nhost])
352         GNUNET_TESTBED_is_host_habitable_cancel (rc->hc_handles[nhost]);
353     GNUNET_free (rc->hc_handles);
354     rc->hc_handles = NULL;
355   }
356   /* Stop register hosts task if it is running */
357   if (GNUNET_SCHEDULER_NO_TASK != rc->register_hosts_task)
358   {
359     GNUNET_SCHEDULER_cancel (rc->register_hosts_task);
360     rc->register_hosts_task = GNUNET_SCHEDULER_NO_TASK;
361   }
362   if (GNUNET_SCHEDULER_NO_TASK != rc->timeout_task)
363   {
364     GNUNET_SCHEDULER_cancel (rc->timeout_task);
365     rc->timeout_task = GNUNET_SCHEDULER_NO_TASK;
366   }
367   if (NULL != rc->reg_handle)
368   {
369     GNUNET_TESTBED_cancel_registration (rc->reg_handle);
370     rc->reg_handle = NULL;
371   }
372   /* cancel any exiting operations */
373   if (NULL != rc->dll_op_head)
374   {
375     while (NULL != (dll_op = rc->dll_op_head))
376     {
377       GNUNET_TESTBED_operation_done (dll_op->op);
378       GNUNET_CONTAINER_DLL_remove (rc->dll_op_head, rc->dll_op_tail, dll_op);
379       GNUNET_free (dll_op);
380     }
381   }
382   if (NULL != rc->c)
383   {
384     if (NULL != rc->peers)
385     {
386       if (NULL != rc->topology_operation)
387       {
388         GNUNET_TESTBED_operation_done (rc->topology_operation);
389         rc->topology_operation = NULL;
390       }
391       if (RC_INIT == rc->state)
392         rc->state = RC_READY;   /* Even though we haven't called the master callback */
393       dll_op = GNUNET_malloc (sizeof (struct DLLOperation));
394       dll_op->op = GNUNET_TESTBED_shutdown_peers (rc->c, dll_op, NULL, NULL);
395       DEBUG ("Shutting down peers\n");
396       rc->pstart_time = GNUNET_TIME_absolute_get ();
397       GNUNET_CONTAINER_DLL_insert_tail (rc->dll_op_head, rc->dll_op_tail,
398                                         dll_op);
399       return;
400     }
401   }
402   rc->state = RC_PEERS_SHUTDOWN;       /* No peers are present so we consider the
403                                         * state where all peers are SHUTDOWN  */
404   GNUNET_SCHEDULER_add_now (&cleanup_task, rc);
405 }
406
407
408 /**
409  * Function to shutdown now
410  *
411  * @param rc the RunContext
412  */
413 static void
414 shutdown_now (struct RunContext *rc)
415 {
416   if (GNUNET_YES == rc->shutdown)
417     return;
418   if (GNUNET_SCHEDULER_NO_TASK != rc->shutdown_run_task)
419     GNUNET_SCHEDULER_cancel (rc->shutdown_run_task);
420   GNUNET_SCHEDULER_shutdown (); /* Trigger shutdown in programs using this API */
421   rc->shutdown_run_task = GNUNET_SCHEDULER_add_now (&shutdown_run, rc);
422 }
423
424
425 /**
426  * Function to return the string representation of the duration between current
427  * time and `pstart_time' in `RunContext'
428  *
429  * @param rc the RunContext
430  * @return the representation string; this is NOT reentrant
431  */
432 static const char *
433 prof_time (struct RunContext *rc)
434 {
435   struct GNUNET_TIME_Relative ptime;
436
437   ptime = GNUNET_TIME_absolute_get_duration (rc->pstart_time);
438   return GNUNET_STRINGS_relative_time_to_string (ptime, GNUNET_YES);
439 }
440
441
442 /**
443  * Task for starting peers
444  *
445  * @param cls the RunHandle
446  * @param tc the task context from scheduler
447  */
448 static void
449 start_peers_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
450 {
451   struct RunContext *rc = cls;
452   struct DLLOperation *dll_op;
453   unsigned int peer;
454
455   DEBUG ("Starting Peers\n");
456   rc->pstart_time = GNUNET_TIME_absolute_get ();
457   for (peer = 0; peer < rc->num_peers; peer++)
458   {
459     dll_op = GNUNET_malloc (sizeof (struct DLLOperation));
460     dll_op->op = GNUNET_TESTBED_peer_start (NULL, rc->peers[peer], NULL, NULL);
461     dll_op->cls = rc->peers[peer];
462     GNUNET_CONTAINER_DLL_insert_tail (rc->dll_op_head, rc->dll_op_tail, dll_op);
463   }
464   rc->peer_count = 0;
465 }
466
467
468 /**
469  * Functions of this signature are called when a peer has been successfully
470  * created
471  *
472  * @param cls the closure from GNUNET_TESTBED_peer_create()
473  * @param peer the handle for the created peer; NULL on any error during
474  *          creation
475  * @param emsg NULL if peer is not NULL; else MAY contain the error description
476  */
477 static void
478 peer_create_cb (void *cls, struct GNUNET_TESTBED_Peer *peer, const char *emsg)
479 {
480   struct DLLOperation *dll_op = cls;
481   struct RunContext *rc;
482
483   GNUNET_assert (NULL != dll_op);
484   rc = dll_op->rc;
485   GNUNET_assert (NULL != rc);
486   GNUNET_CONTAINER_DLL_remove (rc->dll_op_head, rc->dll_op_tail, dll_op);
487   GNUNET_TESTBED_operation_done (dll_op->op);
488   GNUNET_free (dll_op);
489   if (NULL == peer)
490   {
491     if (NULL != emsg)
492       LOG (GNUNET_ERROR_TYPE_ERROR, "Error while creating a peer: %s\n",
493            emsg);
494     shutdown_now (rc);
495     return;
496   }
497   rc->peers[rc->peer_count] = peer;
498   rc->peer_count++;
499   if (rc->peer_count < rc->num_peers)
500     return;
501   DEBUG ("%u peers created in %s\n", rc->num_peers, prof_time (rc));
502   rc->state = RC_PEERS_CREATED;
503   GNUNET_SCHEDULER_add_now (&start_peers_task, rc);
504 }
505
506
507 /**
508  * call test master callback
509  *
510  * @param rc the RunContext
511  */
512 static void
513 call_master (struct RunContext *rc)
514 {
515   GNUNET_SCHEDULER_cancel (rc->timeout_task);
516   rc->timeout_task = GNUNET_SCHEDULER_NO_TASK;
517   if (NULL != rc->test_master)
518     rc->test_master (rc->test_master_cls, rc->num_peers, rc->peers);
519 }
520
521
522 /**
523  * Callbacks of this type are called when topology configuration is completed
524  *
525  * @param cls the operation closure given to
526  *          GNUNET_TESTBED_overlay_configure_topology_va() and
527  *          GNUNET_TESTBED_overlay_configure() calls
528  * @param nsuccess the number of successful overlay connects
529  * @param nfailures the number of overlay connects which failed
530  */
531 static void
532 topology_completion_callback (void *cls, unsigned int nsuccess,
533                               unsigned int nfailures)
534 {
535   struct RunContext *rc = cls;
536
537   DEBUG ("Overlay topology generated in %s\n", prof_time (rc));
538   GNUNET_TESTBED_operation_done (rc->topology_operation);
539   rc->topology_operation = NULL;
540   rc->state = RC_READY;
541   call_master (rc);
542 }
543
544
545 /**
546  * Function to create peers
547  *
548  * @param rc the RunContext
549  */
550 static void
551 create_peers (struct RunContext *rc)
552 {
553   struct DLLOperation *dll_op;
554   unsigned int peer;
555
556   DEBUG ("Creating peers\n");
557   rc->pstart_time = GNUNET_TIME_absolute_get ();
558   rc->peers =
559       GNUNET_malloc (sizeof (struct GNUNET_TESTBED_Peer *) * rc->num_peers);
560   GNUNET_assert (NULL != rc->c);
561   rc->peer_count = 0;
562   for (peer = 0; peer < rc->num_peers; peer++)
563   {
564     dll_op = GNUNET_malloc (sizeof (struct DLLOperation));
565     dll_op->rc = rc;
566     dll_op->op =
567         GNUNET_TESTBED_peer_create (rc->c,
568                                     (0 ==
569                                      rc->num_hosts) ? rc->h : rc->hosts[peer %
570                                                                         rc->num_hosts],
571                                     rc->cfg, peer_create_cb, dll_op);
572     GNUNET_CONTAINER_DLL_insert_tail (rc->dll_op_head, rc->dll_op_tail, dll_op);
573   }
574 }
575
576
577 /**
578  * Signature of the event handler function called by the
579  * respective event controller.
580  *
581  * @param cls closure
582  * @param event information about the event
583  */
584 static void
585 event_cb (void *cls, const struct GNUNET_TESTBED_EventInformation *event)
586 {
587   struct RunContext *rc = cls;
588   struct DLLOperation *dll_op;
589
590   if (RC_INIT == rc->state)
591   {
592     switch (event->type)
593     {
594     case GNUNET_TESTBED_ET_OPERATION_FINISHED:
595       dll_op = event->op_cls;
596       if (NULL != event->details.operation_finished.emsg)
597       {
598         LOG (GNUNET_ERROR_TYPE_ERROR, _("Linking controllers failed. Exiting"));
599         shutdown_now (rc);
600       }
601       else
602         rc->reg_hosts++;
603       GNUNET_assert (event->op == dll_op->op);
604       GNUNET_CONTAINER_DLL_remove (rc->dll_op_head, rc->dll_op_tail, dll_op);
605       GNUNET_TESTBED_operation_done (dll_op->op);
606       GNUNET_free (dll_op);
607       if (rc->reg_hosts == rc->num_hosts)
608       {
609         rc->state = RC_LINKED;
610         create_peers (rc);
611       }
612       return;
613     default:
614       GNUNET_break (0);
615       shutdown_now (rc);
616       return;
617     }
618   }
619   for (dll_op = rc->dll_op_head; NULL != dll_op; dll_op = dll_op->next)
620   {
621     if ((GNUNET_TESTBED_ET_OPERATION_FINISHED == event->type) &&
622         (event->op == dll_op->op))
623       break;
624   }
625   if (NULL == dll_op)
626     goto call_cc;
627   GNUNET_CONTAINER_DLL_remove (rc->dll_op_head, rc->dll_op_tail, dll_op);
628   GNUNET_TESTBED_operation_done (dll_op->op);
629   GNUNET_free (dll_op);
630   if ( (GNUNET_NO == rc->shutdown)
631        && (NULL != event->details.operation_finished.emsg) )
632   {
633     LOG (GNUNET_ERROR_TYPE_ERROR, "A operation has failed with error: %s\n",
634          event->details.operation_finished.emsg);
635     shutdown_now (rc);
636     return;
637   }
638   GNUNET_assert (GNUNET_YES == rc->shutdown);
639   switch (rc->state)
640   {
641   case RC_LINKED:
642   case RC_PEERS_CREATED:
643   case RC_READY:
644     rc->state = RC_PEERS_SHUTDOWN;
645     GNUNET_free_non_null (rc->peers);
646     rc->peers = NULL;
647     DEBUG ("Peers shut down in %s\n", prof_time (rc));
648     GNUNET_SCHEDULER_add_now (&cleanup_task, rc);
649     break;
650   default:
651     GNUNET_assert (0);
652   }
653   return;
654
655 call_cc:
656   if ((0 != (rc->event_mask & (1LL << event->type))) && (NULL != rc->cc))
657     rc->cc (rc->cc_cls, event);
658   if (GNUNET_TESTBED_ET_PEER_START != event->type)
659     return;
660   for (dll_op = rc->dll_op_head; NULL != dll_op; dll_op = dll_op->next)
661     if ((NULL != dll_op->cls) &&
662         (event->details.peer_start.peer == dll_op->cls))
663       break;
664   if (NULL == dll_op)           /* Not our operation */
665     return;
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   rc->peer_count++;
670   if (rc->peer_count < rc->num_peers)
671     return;
672   DEBUG ("%u peers started in %s\n", rc->num_peers, prof_time (rc));
673   if (GNUNET_TESTBED_TOPOLOGY_NONE != rc->topology)
674   {
675     if ((GNUNET_TESTBED_TOPOLOGY_ERDOS_RENYI == rc->topology) ||
676         (GNUNET_TESTBED_TOPOLOGY_SMALL_WORLD_RING == rc->topology) ||
677         (GNUNET_TESTBED_TOPOLOGY_SMALL_WORLD == rc->topology))
678     {
679       rc->topology_operation =
680           GNUNET_TESTBED_overlay_configure_topology (NULL, rc->num_peers,
681                                                      rc->peers, &rc->num_oc,
682                                                      &topology_completion_callback,
683                                                      rc,
684                                                      rc->topology,
685                                                      rc->random_links,
686                                                      GNUNET_TESTBED_TOPOLOGY_OPTION_END);
687     }
688     else if (GNUNET_TESTBED_TOPOLOGY_FROM_FILE == rc->topology)
689     {
690       GNUNET_assert (NULL != rc->topo_file);
691       rc->topology_operation =
692           GNUNET_TESTBED_overlay_configure_topology (NULL, rc->num_peers,
693                                                      rc->peers, &rc->num_oc,
694                                                      &topology_completion_callback,
695                                                      rc,
696                                                      rc->topology,
697                                                      rc->topo_file,
698                                                      GNUNET_TESTBED_TOPOLOGY_OPTION_END);
699     }
700     else
701       rc->topology_operation =
702           GNUNET_TESTBED_overlay_configure_topology (NULL, rc->num_peers,
703                                                      rc->peers, &rc->num_oc,
704                                                      &topology_completion_callback,
705                                                      rc,
706                                                      rc->topology,
707                                                      GNUNET_TESTBED_TOPOLOGY_OPTION_END);
708     if (NULL == rc->topology_operation)
709       LOG (GNUNET_ERROR_TYPE_WARNING,
710            "Not generating topology. Check number of peers\n");
711     else
712     {
713       DEBUG ("Creating overlay topology\n");
714       rc->pstart_time = GNUNET_TIME_absolute_get ();
715       return;
716     }
717   }
718   rc->state = RC_READY;
719   call_master (rc);
720 }
721
722
723 /**
724  * Task to register all hosts available in the global host list
725  *
726  * @param cls the RunContext
727  * @param tc the scheduler task context
728  */
729 static void
730 register_hosts (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
731
732
733 /**
734  * Callback which will be called to after a host registration succeeded or failed
735  *
736  * @param cls the closure
737  * @param emsg the error message; NULL if host registration is successful
738  */
739 static void
740 host_registration_completion (void *cls, const char *emsg)
741 {
742   struct RunContext *rc = cls;
743
744   rc->reg_handle = NULL;
745   if (NULL != emsg)
746   {
747     LOG (GNUNET_ERROR_TYPE_WARNING,
748          _("Host registration failed for a host. Error: %s\n"), emsg);
749     shutdown_now (rc);
750     return;
751   }
752   rc->register_hosts_task = GNUNET_SCHEDULER_add_now (&register_hosts, rc);
753 }
754
755
756 /**
757  * Task to register all hosts available in the global host list
758  *
759  * @param cls RunContext
760  * @param tc the scheduler task context
761  */
762 static void
763 register_hosts (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
764 {
765   struct RunContext *rc = cls;
766   struct DLLOperation *dll_op;
767   unsigned int slave;
768
769   rc->register_hosts_task = GNUNET_SCHEDULER_NO_TASK;
770   if (rc->reg_hosts == rc->num_hosts)
771   {
772     DEBUG ("All hosts successfully registered\n");
773     /* Start slaves */
774     for (slave = 0; slave < rc->num_hosts; slave++)
775     {
776       dll_op = GNUNET_malloc (sizeof (struct DLLOperation));
777       dll_op->rc = rc;
778       dll_op->op =
779           GNUNET_TESTBED_controller_link (dll_op, rc->c, rc->hosts[slave],
780                                           rc->h, rc->cfg, GNUNET_YES);
781       GNUNET_CONTAINER_DLL_insert_tail (rc->dll_op_head, rc->dll_op_tail,
782                                         dll_op);
783     }
784     rc->reg_hosts = 0;
785     return;
786   }
787   rc->reg_handle =
788       GNUNET_TESTBED_register_host (rc->c, rc->hosts[rc->reg_hosts],
789                                     host_registration_completion, rc);
790   rc->reg_hosts++;
791 }
792
793
794 /**
795  * Callback to signal successfull startup of the controller process
796  *
797  * @param cls the closure from GNUNET_TESTBED_controller_start()
798  * @param cfg the configuration with which the controller has been started;
799  *          NULL if status is not GNUNET_OK
800  * @param status GNUNET_OK if the startup is successfull; GNUNET_SYSERR if not,
801  *          GNUNET_TESTBED_controller_stop() shouldn't be called in this case
802  */
803 static void
804 controller_status_cb (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg,
805                       int status)
806 {
807   struct RunContext *rc = cls;
808   uint64_t event_mask;
809
810   if (status != GNUNET_OK)
811   {
812     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
813                 _("Controller crash detected. Shutting down.\n"));
814     rc->cproc = NULL;
815     if (NULL != rc->peers)
816     {
817       GNUNET_free (rc->peers);
818       rc->peers = NULL;
819     }
820     shutdown_now (rc);
821     return;
822   }
823   GNUNET_CONFIGURATION_destroy (rc->cfg);
824   rc->cfg = GNUNET_CONFIGURATION_dup (cfg);
825   event_mask = rc->event_mask;
826   event_mask |= (1LL << GNUNET_TESTBED_ET_OPERATION_FINISHED);
827   event_mask |= (1LL << GNUNET_TESTBED_ET_PEER_START);
828   if (rc->topology < GNUNET_TESTBED_TOPOLOGY_NONE)
829     event_mask |= GNUNET_TESTBED_ET_CONNECT;
830   rc->c =
831       GNUNET_TESTBED_controller_connect (rc->cfg, rc->h, event_mask, &event_cb,
832                                          rc);
833   if (0 < rc->num_hosts)
834   {
835     rc->reg_hosts = 0;
836     rc->register_hosts_task = GNUNET_SCHEDULER_add_now (&register_hosts, rc);
837     return;
838   }
839   rc->state = RC_LINKED;
840   create_peers (rc);
841 }
842
843
844 /**
845  * Callback function invoked for each interface found.
846  *
847  * @param cls closure
848  * @param name name of the interface (can be NULL for unknown)
849  * @param isDefault is this presumably the default interface
850  * @param addr address of this interface (can be NULL for unknown or unassigned)
851  * @param broadcast_addr the broadcast address (can be NULL for unknown or unassigned)
852  * @param netmask the network mask (can be NULL for unknown or unassigned))
853  * @param addrlen length of the address
854  * @return GNUNET_OK to continue iteration, GNUNET_SYSERR to abort
855  */
856 static int
857 netint_proc (void *cls, const char *name, int isDefault,
858              const struct sockaddr *addr, const struct sockaddr *broadcast_addr,
859              const struct sockaddr *netmask, socklen_t addrlen)
860 {
861   struct RunContext *rc = cls;
862   char hostip[NI_MAXHOST];
863   char *buf;
864
865   if (sizeof (struct sockaddr_in) != addrlen)
866     return GNUNET_OK;           /* Only consider IPv4 for now */
867   if (0 !=
868       getnameinfo (addr, addrlen, hostip, NI_MAXHOST, NULL, 0, NI_NUMERICHOST))
869     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "getnameinfo");
870   if (NULL == rc->trusted_ip)
871   {
872     rc->trusted_ip = GNUNET_strdup (hostip);
873     return GNUNET_YES;
874   }
875   (void) GNUNET_asprintf (&buf, "%s; %s", rc->trusted_ip, hostip);
876   GNUNET_free (rc->trusted_ip);
877   rc->trusted_ip = buf;
878   return GNUNET_YES;
879 }
880
881
882 /**
883  * Callbacks of this type are called by GNUNET_TESTBED_is_host_habitable to
884  * inform whether the given host is habitable or not. The Handle returned by
885  * GNUNET_TESTBED_is_host_habitable() is invalid after this callback is called
886  *
887  * @param cls NULL
888  * @param host the host whose status is being reported; will be NULL if the host
889  *          given to GNUNET_TESTBED_is_host_habitable() is NULL
890  * @param status GNUNET_YES if it is habitable; GNUNET_NO if not
891  */
892 static void
893 host_habitable_cb (void *cls, const struct GNUNET_TESTBED_Host *host,
894                    int status)
895 {
896   struct RunContext *rc = cls;
897   struct GNUNET_TESTBED_Host **old_hosts;
898   unsigned int nhost;
899
900   for (nhost = 0; nhost < rc->num_hosts; nhost++)
901   {
902     if (host == rc->hosts[nhost])
903       break;
904   }
905   GNUNET_assert (nhost != rc->num_hosts);
906   rc->hc_handles[nhost] = NULL;
907   if (GNUNET_NO == status)
908   {
909     if ((NULL != host) && (NULL != GNUNET_TESTBED_host_get_hostname (host)))
910       LOG (GNUNET_ERROR_TYPE_ERROR, _("Host %s cannot start testbed\n"),
911            GNUNET_TESTBED_host_get_hostname (host));
912     else
913       LOG (GNUNET_ERROR_TYPE_ERROR,
914            _("Testbed cannot be started on localhost\n"));
915     shutdown_now (rc);
916     return;
917   }
918   rc->reg_hosts++;
919   if (rc->reg_hosts < rc->num_hosts)
920     return;
921   GNUNET_free (rc->hc_handles);
922   rc->hc_handles = NULL;
923   rc->h = rc->hosts[0];
924   rc->num_hosts--;
925   if (0 < rc->num_hosts)
926   {
927     old_hosts = rc->hosts;
928     rc->hosts =
929         GNUNET_malloc (sizeof (struct GNUNET_TESTBED_Host *) * rc->num_hosts);
930     memcpy (rc->hosts, &old_hosts[1],
931             (sizeof (struct GNUNET_TESTBED_Host *) * rc->num_hosts));
932     GNUNET_free (old_hosts);
933   }
934   else
935   {
936     GNUNET_free (rc->hosts);
937     rc->hosts = NULL;
938   }
939   GNUNET_OS_network_interfaces_list (netint_proc, rc);
940   if (NULL == rc->trusted_ip)
941     rc->trusted_ip = GNUNET_strdup ("127.0.0.1");
942   rc->cproc =
943       GNUNET_TESTBED_controller_start (rc->trusted_ip, rc->h, rc->cfg,
944                                        &controller_status_cb, rc);
945   GNUNET_free (rc->trusted_ip);
946   rc->trusted_ip = NULL;
947   if (NULL == rc->cproc)
948   {
949     LOG (GNUNET_ERROR_TYPE_ERROR, _("Cannot start the master controller"));
950     shutdown_now (rc);
951   }
952 }
953
954
955 /**
956  * Task run upon timeout while setting up the testbed
957  *
958  * @param cls the RunContext
959  * @param tc the task context
960  */
961 static void
962 timeout_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
963 {
964   struct RunContext *rc = cls;
965   
966   rc->timeout_task = GNUNET_SCHEDULER_NO_TASK;
967   LOG (GNUNET_ERROR_TYPE_ERROR, _("Shutting down testbed due to timeout while setup.\n"));
968   shutdown_now (rc);
969    if (NULL != rc->test_master)
970     rc->test_master (rc->test_master_cls, 0, NULL);
971    rc->test_master = NULL;
972 }
973
974
975 /**
976  * Convenience method for running a testbed with
977  * a single call.  Underlay and overlay topology
978  * are configured using the "UNDERLAY" and "OVERLAY"
979  * options in the "[testbed]" section of the configuration\
980  * (with possible options given in "UNDERLAY_XXX" and/or
981  * "OVERLAY_XXX").
982  *
983  * The testbed is to be terminated using a call to
984  * "GNUNET_SCHEDULER_shutdown".
985  *
986  * @param host_filename name of the file with the 'hosts', NULL
987  *        to run everything on 'localhost'
988  * @param cfg configuration to use (for testbed, controller and peers)
989  * @param num_peers number of peers to start; FIXME: maybe put that ALSO into cfg?
990  * @param event_mask bit mask with set of events to call 'cc' for;
991  *                   or-ed values of "1LL" shifted by the
992  *                   respective 'enum GNUNET_TESTBED_EventType'
993  *                   (i.e.  "(1LL << GNUNET_TESTBED_ET_CONNECT) || ...")
994  * @param cc controller callback to invoke on events; This callback is called
995  *          for all peer start events even if GNUNET_TESTBED_ET_PEER_START isn't
996  *          set in the event_mask as this is the only way get access to the
997  *          handle of each peer
998  * @param cc_cls closure for cc
999  * @param test_master this callback will be called once the test is ready
1000  * @param test_master_cls closure for 'test_master'.
1001  */
1002 void
1003 GNUNET_TESTBED_run (const char *host_filename,
1004                     const struct GNUNET_CONFIGURATION_Handle *cfg,
1005                     unsigned int num_peers, uint64_t event_mask,
1006                     GNUNET_TESTBED_ControllerCallback cc, void *cc_cls,
1007                     GNUNET_TESTBED_TestMaster test_master,
1008                     void *test_master_cls)
1009 {
1010   struct RunContext *rc;
1011   char *topology;
1012   struct GNUNET_TIME_Relative timeout;
1013   unsigned long long random_links;
1014   unsigned int hid;
1015   unsigned int nhost;
1016
1017   GNUNET_assert (num_peers > 0);
1018   rc = GNUNET_malloc (sizeof (struct RunContext));
1019   rc->cfg = GNUNET_CONFIGURATION_dup (cfg);
1020 #if ENABLE_LL
1021   rc->num_hosts = GNUNET_TESTBED_hosts_load_from_loadleveler (rc->cfg,
1022                                                               &rc->hosts);
1023   if (0 == rc->num_hosts)
1024   {
1025     LOG (GNUNET_ERROR_TYPE_WARNING,
1026            _("No hosts loaded from LoadLeveler. Need at least one host\n"));
1027     goto error_cleanup;
1028   }
1029 #else
1030   if (NULL != host_filename)
1031   {
1032     rc->num_hosts =
1033         GNUNET_TESTBED_hosts_load_from_file (host_filename, rc->cfg,
1034                                              &rc->hosts);
1035     if (0 == rc->num_hosts)
1036     {
1037       LOG (GNUNET_ERROR_TYPE_WARNING,
1038            _("No hosts loaded. Need at least one host\n"));
1039       goto error_cleanup;
1040     }
1041   }
1042   else
1043     rc->h = GNUNET_TESTBED_host_create (NULL, NULL, rc->cfg, 0);
1044 #endif
1045   rc->num_peers = num_peers;
1046   rc->event_mask = event_mask;
1047   rc->cc = cc;
1048   rc->cc_cls = cc_cls;
1049   rc->test_master = test_master;
1050   rc->test_master_cls = test_master_cls;
1051   rc->state = RC_INIT;
1052   rc->topology = GNUNET_TESTBED_TOPOLOGY_NONE;
1053   if (GNUNET_OK ==
1054       GNUNET_CONFIGURATION_get_value_string (rc->cfg, "testbed",
1055                                              "OVERLAY_TOPOLOGY", &topology))
1056   {
1057     if (GNUNET_NO == GNUNET_TESTBED_topology_get_ (&rc->topology, topology))
1058     {
1059       GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR, "testbed",
1060                                  "OVERLAY_TOPLOGY",
1061                                  _
1062                                  ("Specified topology must be supported by testbed"));
1063     }
1064     GNUNET_free (topology);
1065   }
1066   switch (rc->topology)
1067   {
1068   case GNUNET_TESTBED_TOPOLOGY_ERDOS_RENYI:
1069   case GNUNET_TESTBED_TOPOLOGY_SMALL_WORLD_RING:
1070   case GNUNET_TESTBED_TOPOLOGY_SMALL_WORLD:
1071     if (GNUNET_OK !=
1072         GNUNET_CONFIGURATION_get_value_number (rc->cfg, "testbed",
1073                                                "OVERLAY_RANDOM_LINKS",
1074                                                &random_links))
1075     {
1076       /* OVERLAY option RANDOM & SMALL_WORLD_RING requires OVERLAY_RANDOM_LINKS
1077        * option to be set to the number of random links to be established  */
1078       GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, "testbed",
1079                                  "OVERLAY_RANDOM_LINKS");
1080       goto error_cleanup;
1081     }
1082     if (random_links > UINT32_MAX)
1083     {
1084       GNUNET_break (0);         /* Too big number */
1085       goto error_cleanup;
1086     }
1087     rc->random_links = (unsigned int) random_links;
1088     break;
1089   case GNUNET_TESTBED_TOPOLOGY_FROM_FILE:
1090     if (GNUNET_OK !=
1091         GNUNET_CONFIGURATION_get_value_string (rc->cfg, "testbed",
1092                                                "OVERLAY_TOPOLOGY_FILE",
1093                                                &rc->topo_file))
1094     {
1095       GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, "testbed",
1096                                  "OVERLAY_TOPOLOGY_FILE");
1097       goto error_cleanup;
1098     }
1099   default:
1100     /* Warn if OVERLAY_RANDOM_LINKS is present that it will be ignored */
1101     if (GNUNET_YES ==
1102         GNUNET_CONFIGURATION_have_value (rc->cfg, "testbed",
1103                                          "OVERLAY_RANDOM_LINKS"))
1104       LOG (GNUNET_ERROR_TYPE_WARNING,
1105            "Ignoring value of `OVERLAY_RANDOM_LINKS' in given configuration\n");
1106     break;
1107   }
1108   if (0 != rc->num_hosts)
1109   {
1110     rc->hc_handles =
1111         GNUNET_malloc (sizeof (struct GNUNET_TESTBED_HostHabitableCheckHandle *)
1112                        * rc->num_hosts);
1113     for (nhost = 0; nhost < rc->num_hosts; nhost++)
1114     {
1115       if (NULL ==
1116           (rc->hc_handles[nhost] =
1117            GNUNET_TESTBED_is_host_habitable (rc->hosts[nhost], rc->cfg,
1118                                              &host_habitable_cb, rc)))
1119       {
1120         GNUNET_break (0);
1121         for (nhost = 0; nhost < rc->num_hosts; nhost++)
1122           if (NULL != rc->hc_handles[nhost])
1123             GNUNET_TESTBED_is_host_habitable_cancel (rc->hc_handles[nhost]);
1124         GNUNET_free (rc->hc_handles);
1125         rc->hc_handles = NULL;
1126         goto error_cleanup;
1127       }
1128     }
1129   }
1130   else
1131     rc->cproc =
1132         GNUNET_TESTBED_controller_start ("127.0.0.1", rc->h, rc->cfg,
1133                                          &controller_status_cb, rc);
1134   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_time (cfg, "TESTBED",
1135                                                         "SETUP_TIMEOUT",
1136                                                         &timeout))
1137   {
1138     timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
1139                                              DEFAULT_SETUP_TIMEOUT);
1140   }
1141   rc->timeout_task =
1142       GNUNET_SCHEDULER_add_delayed (timeout, &timeout_task, rc);
1143   rc->shutdown_run_task =
1144       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_run,
1145                                     rc);
1146   return;
1147
1148 error_cleanup:
1149   if (NULL != rc->h)
1150     GNUNET_TESTBED_host_destroy (rc->h);
1151   if (NULL != rc->hosts)
1152   {
1153     for (hid = 0; hid < rc->num_hosts; hid++)
1154       if (NULL != rc->hosts[hid])
1155         GNUNET_TESTBED_host_destroy (rc->hosts[hid]);
1156     GNUNET_free (rc->hosts);
1157   }
1158   if (NULL != rc->cfg)
1159     GNUNET_CONFIGURATION_destroy (rc->cfg);
1160   GNUNET_free (rc);
1161 }
1162
1163
1164 /* end of testbed_api_testbed.c */