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