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