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