- use host's configuration while connecting to controller
[oweals/gnunet.git] / src / testbed / testbed_api_testbed.c
1 /*
2   This file is part of GNUnet
3   (C) 2008--2013 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->h, event_mask, &event_cb, rc);
879   if (0 < rc->num_hosts)
880   {
881     rc->reg_hosts = 0;
882     rc->register_hosts_task = GNUNET_SCHEDULER_add_now (&register_hosts, rc);
883     return;
884   }
885   rc->state = RC_LINKED;
886   create_peers (rc);
887 }
888
889
890 /**
891  * Callback function invoked for each interface found.
892  *
893  * @param cls closure
894  * @param name name of the interface (can be NULL for unknown)
895  * @param isDefault is this presumably the default interface
896  * @param addr address of this interface (can be NULL for unknown or unassigned)
897  * @param broadcast_addr the broadcast address (can be NULL for unknown or unassigned)
898  * @param netmask the network mask (can be NULL for unknown or unassigned))
899  * @param addrlen length of the address
900  * @return GNUNET_OK to continue iteration, GNUNET_SYSERR to abort
901  */
902 static int
903 netint_proc (void *cls, const char *name, int isDefault,
904              const struct sockaddr *addr, const struct sockaddr *broadcast_addr,
905              const struct sockaddr *netmask, socklen_t addrlen)
906 {
907   struct RunContext *rc = cls;
908   char hostip[NI_MAXHOST];
909   char *buf;
910
911   if (sizeof (struct sockaddr_in) != addrlen)
912     return GNUNET_OK;           /* Only consider IPv4 for now */
913   if (0 !=
914       getnameinfo (addr, addrlen, hostip, NI_MAXHOST, NULL, 0, NI_NUMERICHOST))
915     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "getnameinfo");
916   if (NULL == rc->trusted_ip)
917   {
918     rc->trusted_ip = GNUNET_strdup (hostip);
919     return GNUNET_YES;
920   }
921   (void) GNUNET_asprintf (&buf, "%s; %s", rc->trusted_ip, hostip);
922   GNUNET_free (rc->trusted_ip);
923   rc->trusted_ip = buf;
924   return GNUNET_YES;
925 }
926
927
928 /**
929  * Callbacks of this type are called by GNUNET_TESTBED_is_host_habitable to
930  * inform whether the given host is habitable or not. The Handle returned by
931  * GNUNET_TESTBED_is_host_habitable() is invalid after this callback is called
932  *
933  * @param cls NULL
934  * @param host the host whose status is being reported; will be NULL if the host
935  *          given to GNUNET_TESTBED_is_host_habitable() is NULL
936  * @param status GNUNET_YES if it is habitable; GNUNET_NO if not
937  */
938 static void
939 host_habitable_cb (void *cls, const struct GNUNET_TESTBED_Host *host,
940                    int status)
941 {
942   struct RunContext *rc = cls;
943   struct GNUNET_TESTBED_Host **old_hosts;
944   unsigned int nhost;
945
946   for (nhost = 0; nhost < rc->num_hosts; nhost++)
947   {
948     if (host == rc->hosts[nhost])
949       break;
950   }
951   GNUNET_assert (nhost != rc->num_hosts);
952   rc->hc_handles[nhost] = NULL;
953   if (GNUNET_NO == status)
954   {
955     if ((NULL != host) && (NULL != GNUNET_TESTBED_host_get_hostname (host)))
956       LOG (GNUNET_ERROR_TYPE_ERROR, _("Host %s cannot start testbed\n"),
957            GNUNET_TESTBED_host_get_hostname (host));
958     else
959       LOG (GNUNET_ERROR_TYPE_ERROR,
960            _("Testbed cannot be started on localhost\n"));
961     shutdown_now (rc);
962     return;
963   }
964   rc->reg_hosts++;
965   if (rc->reg_hosts < rc->num_hosts)
966     return;
967   GNUNET_free (rc->hc_handles);
968   rc->hc_handles = NULL;
969   rc->h = rc->hosts[0];
970   rc->num_hosts--;
971   if (0 < rc->num_hosts)
972   {
973     old_hosts = rc->hosts;
974     rc->hosts =
975         GNUNET_malloc (sizeof (struct GNUNET_TESTBED_Host *) * rc->num_hosts);
976     memcpy (rc->hosts, &old_hosts[1],
977             (sizeof (struct GNUNET_TESTBED_Host *) * rc->num_hosts));
978     GNUNET_free (old_hosts);
979   }
980   else
981   {
982     GNUNET_free (rc->hosts);
983     rc->hosts = NULL;
984   }
985   GNUNET_OS_network_interfaces_list (netint_proc, rc);
986   if (NULL == rc->trusted_ip)
987     rc->trusted_ip = GNUNET_strdup ("127.0.0.1");
988   rc->cproc =
989       GNUNET_TESTBED_controller_start (rc->trusted_ip, rc->h, rc->cfg,
990                                        &controller_status_cb, rc);
991   GNUNET_free (rc->trusted_ip);
992   rc->trusted_ip = NULL;
993   if (NULL == rc->cproc)
994   {
995     LOG (GNUNET_ERROR_TYPE_ERROR, _("Cannot start the master controller"));
996     shutdown_now (rc);
997   }
998 }
999
1000
1001 /**
1002  * Task run upon timeout while setting up the testbed
1003  *
1004  * @param cls the RunContext
1005  * @param tc the task context
1006  */
1007 static void
1008 timeout_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1009 {
1010   struct RunContext *rc = cls;
1011   
1012   rc->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1013   LOG (GNUNET_ERROR_TYPE_ERROR, _("Shutting down testbed due to timeout while setup.\n"));
1014   shutdown_now (rc);
1015    if (NULL != rc->test_master)
1016      rc->test_master (rc->test_master_cls, 0, NULL, 0, 0);
1017    rc->test_master = NULL;
1018 }
1019
1020
1021 /**
1022  * Convenience method for running a testbed with
1023  * a single call.  Underlay and overlay topology
1024  * are configured using the "UNDERLAY" and "OVERLAY"
1025  * options in the "[testbed]" section of the configuration\
1026  * (with possible options given in "UNDERLAY_XXX" and/or
1027  * "OVERLAY_XXX").
1028  *
1029  * The testbed is to be terminated using a call to
1030  * "GNUNET_SCHEDULER_shutdown".
1031  *
1032  * @param host_filename name of the file with the 'hosts', NULL
1033  *        to run everything on 'localhost'
1034  * @param cfg configuration to use (for testbed, controller and peers)
1035  * @param num_peers number of peers to start; FIXME: maybe put that ALSO into cfg?
1036  * @param event_mask bit mask with set of events to call 'cc' for;
1037  *                   or-ed values of "1LL" shifted by the
1038  *                   respective 'enum GNUNET_TESTBED_EventType'
1039  *                   (i.e.  "(1LL << GNUNET_TESTBED_ET_CONNECT) || ...")
1040  * @param cc controller callback to invoke on events; This callback is called
1041  *          for all peer start events even if GNUNET_TESTBED_ET_PEER_START isn't
1042  *          set in the event_mask as this is the only way get access to the
1043  *          handle of each peer
1044  * @param cc_cls closure for cc
1045  * @param test_master this callback will be called once the test is ready
1046  * @param test_master_cls closure for 'test_master'.
1047  */
1048 void
1049 GNUNET_TESTBED_run (const char *host_filename,
1050                     const struct GNUNET_CONFIGURATION_Handle *cfg,
1051                     unsigned int num_peers, uint64_t event_mask,
1052                     GNUNET_TESTBED_ControllerCallback cc, void *cc_cls,
1053                     GNUNET_TESTBED_TestMaster test_master,
1054                     void *test_master_cls)
1055 {
1056   struct RunContext *rc;
1057   char *topology;
1058   struct GNUNET_TIME_Relative timeout;
1059   unsigned long long random_links;
1060   unsigned int hid;
1061   unsigned int nhost;
1062
1063   GNUNET_assert (num_peers > 0);
1064   rc = GNUNET_malloc (sizeof (struct RunContext));
1065   rc->cfg = GNUNET_CONFIGURATION_dup (cfg);
1066 #if ENABLE_LL
1067   rc->num_hosts = GNUNET_TESTBED_hosts_load_from_loadleveler (rc->cfg,
1068                                                               &rc->hosts);
1069   if (0 == rc->num_hosts)
1070   {
1071     LOG (GNUNET_ERROR_TYPE_WARNING,
1072            _("No hosts loaded from LoadLeveler. Need at least one host\n"));
1073     goto error_cleanup;
1074   }
1075 #else
1076   if (NULL != host_filename)
1077   {
1078     rc->num_hosts =
1079         GNUNET_TESTBED_hosts_load_from_file (host_filename, rc->cfg,
1080                                              &rc->hosts);
1081     if (0 == rc->num_hosts)
1082     {
1083       LOG (GNUNET_ERROR_TYPE_WARNING,
1084            _("No hosts loaded. Need at least one host\n"));
1085       goto error_cleanup;
1086     }
1087   }
1088   else
1089     rc->h = GNUNET_TESTBED_host_create (NULL, NULL, rc->cfg, 0);
1090 #endif
1091   rc->num_peers = num_peers;
1092   rc->event_mask = event_mask;
1093   rc->cc = cc;
1094   rc->cc_cls = cc_cls;
1095   rc->test_master = test_master;
1096   rc->test_master_cls = test_master_cls;
1097   rc->state = RC_INIT;
1098   rc->topology = GNUNET_TESTBED_TOPOLOGY_NONE;
1099   if (GNUNET_OK ==
1100       GNUNET_CONFIGURATION_get_value_string (rc->cfg, "testbed",
1101                                              "OVERLAY_TOPOLOGY", &topology))
1102   {
1103     if (GNUNET_NO == GNUNET_TESTBED_topology_get_ (&rc->topology, topology))
1104     {
1105       GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR, "testbed",
1106                                  "OVERLAY_TOPLOGY",
1107                                  _
1108                                  ("Specified topology must be supported by testbed"));
1109     }
1110     GNUNET_free (topology);
1111   }
1112   switch (rc->topology)
1113   {
1114   case GNUNET_TESTBED_TOPOLOGY_ERDOS_RENYI:
1115   case GNUNET_TESTBED_TOPOLOGY_SMALL_WORLD_RING:
1116   case GNUNET_TESTBED_TOPOLOGY_SMALL_WORLD:
1117     if (GNUNET_OK !=
1118         GNUNET_CONFIGURATION_get_value_number (rc->cfg, "testbed",
1119                                                "OVERLAY_RANDOM_LINKS",
1120                                                &random_links))
1121     {
1122       /* OVERLAY option RANDOM & SMALL_WORLD_RING requires OVERLAY_RANDOM_LINKS
1123        * option to be set to the number of random links to be established  */
1124       GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, "testbed",
1125                                  "OVERLAY_RANDOM_LINKS");
1126       goto error_cleanup;
1127     }
1128     if (random_links > UINT32_MAX)
1129     {
1130       GNUNET_break (0);         /* Too big number */
1131       goto error_cleanup;
1132     }
1133     rc->random_links = (unsigned int) random_links;
1134     break;
1135   case GNUNET_TESTBED_TOPOLOGY_FROM_FILE:
1136     if (GNUNET_OK !=
1137         GNUNET_CONFIGURATION_get_value_string (rc->cfg, "testbed",
1138                                                "OVERLAY_TOPOLOGY_FILE",
1139                                                &rc->topo_file))
1140     {
1141       GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, "testbed",
1142                                  "OVERLAY_TOPOLOGY_FILE");
1143       goto error_cleanup;
1144     }
1145   default:
1146     /* Warn if OVERLAY_RANDOM_LINKS is present that it will be ignored */
1147     if (GNUNET_YES ==
1148         GNUNET_CONFIGURATION_have_value (rc->cfg, "testbed",
1149                                          "OVERLAY_RANDOM_LINKS"))
1150       LOG (GNUNET_ERROR_TYPE_WARNING,
1151            "Ignoring value of `OVERLAY_RANDOM_LINKS' in given configuration\n");
1152     break;
1153   }
1154   if (0 != rc->num_hosts)
1155   {
1156     rc->hc_handles =
1157         GNUNET_malloc (sizeof (struct GNUNET_TESTBED_HostHabitableCheckHandle *)
1158                        * rc->num_hosts);
1159     for (nhost = 0; nhost < rc->num_hosts; nhost++)
1160     {
1161       if (NULL ==
1162           (rc->hc_handles[nhost] =
1163            GNUNET_TESTBED_is_host_habitable (rc->hosts[nhost], rc->cfg,
1164                                              &host_habitable_cb, rc)))
1165       {
1166         GNUNET_break (0);
1167         for (nhost = 0; nhost < rc->num_hosts; nhost++)
1168           if (NULL != rc->hc_handles[nhost])
1169             GNUNET_TESTBED_is_host_habitable_cancel (rc->hc_handles[nhost]);
1170         GNUNET_free (rc->hc_handles);
1171         rc->hc_handles = NULL;
1172         goto error_cleanup;
1173       }
1174     }
1175   }
1176   else
1177     rc->cproc =
1178         GNUNET_TESTBED_controller_start ("127.0.0.1", rc->h, rc->cfg,
1179                                          &controller_status_cb, rc);
1180   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_time (cfg, "TESTBED",
1181                                                         "SETUP_TIMEOUT",
1182                                                         &timeout))
1183   {
1184     timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
1185                                              DEFAULT_SETUP_TIMEOUT);
1186   }
1187   rc->timeout_task =
1188       GNUNET_SCHEDULER_add_delayed (timeout, &timeout_task, rc);
1189   rc->interrupt_task =
1190       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &interrupt,
1191                                     rc);
1192   return;
1193
1194 error_cleanup:
1195   if (NULL != rc->h)
1196     GNUNET_TESTBED_host_destroy (rc->h);
1197   if (NULL != rc->hosts)
1198   {
1199     for (hid = 0; hid < rc->num_hosts; hid++)
1200       if (NULL != rc->hosts[hid])
1201         GNUNET_TESTBED_host_destroy (rc->hosts[hid]);
1202     GNUNET_free (rc->hosts);
1203   }
1204   if (NULL != rc->cfg)
1205     GNUNET_CONFIGURATION_destroy (rc->cfg);
1206   GNUNET_free (rc);
1207 }
1208
1209
1210 /* end of testbed_api_testbed.c */