- check whether an operation gets cleaned before calling secondary callback
[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                                                      rc->topology,
739                                                      rc->random_links,
740                                                      GNUNET_TESTBED_TOPOLOGY_OPTION_END);
741     }
742     else if (GNUNET_TESTBED_TOPOLOGY_FROM_FILE == rc->topology)
743     {
744       GNUNET_assert (NULL != rc->topo_file);
745       rc->topology_operation =
746           GNUNET_TESTBED_overlay_configure_topology (NULL, rc->num_peers,
747                                                      rc->peers, &rc->num_oc,
748                                                      rc->topology,
749                                                      rc->topo_file,
750                                                      GNUNET_TESTBED_TOPOLOGY_OPTION_END);
751     }
752     else
753       rc->topology_operation =
754           GNUNET_TESTBED_overlay_configure_topology (NULL, rc->num_peers,
755                                                      rc->peers, &rc->num_oc,
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   if (NULL != host_filename)
1053   {
1054     rc->num_hosts =
1055         GNUNET_TESTBED_hosts_load_from_file (host_filename, &rc->hosts);
1056     if (0 == rc->num_hosts)
1057     {
1058       LOG (GNUNET_ERROR_TYPE_WARNING,
1059            _("No hosts loaded. Need at least one host\n"));
1060       goto error_cleanup;
1061     }
1062   }
1063   else
1064     rc->h = GNUNET_TESTBED_host_create (NULL, NULL, 0);
1065   rc->cfg = GNUNET_CONFIGURATION_dup (cfg);
1066   rc->num_peers = num_peers;
1067   rc->event_mask = event_mask;
1068   rc->cc = cc;
1069   rc->cc_cls = cc_cls;
1070   rc->test_master = test_master;
1071   rc->test_master_cls = test_master_cls;
1072   rc->state = RC_INIT;
1073   rc->topology = GNUNET_TESTBED_TOPOLOGY_NONE;
1074   if (GNUNET_OK ==
1075       GNUNET_CONFIGURATION_get_value_string (rc->cfg, "testbed",
1076                                              "OVERLAY_TOPOLOGY", &topology))
1077   {
1078     if (GNUNET_NO == GNUNET_TESTBED_topology_get_ (&rc->topology, topology))
1079     {
1080       GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR, "testbed",
1081                                  "OVERLAY_TOPLOGY",
1082                                  _
1083                                  ("Specified topology must be supported by testbed"));
1084     }
1085     GNUNET_free (topology);
1086   }
1087   switch (rc->topology)
1088   {
1089   case GNUNET_TESTBED_TOPOLOGY_ERDOS_RENYI:
1090   case GNUNET_TESTBED_TOPOLOGY_SMALL_WORLD_RING:
1091   case GNUNET_TESTBED_TOPOLOGY_SMALL_WORLD:
1092     if (GNUNET_OK !=
1093         GNUNET_CONFIGURATION_get_value_number (rc->cfg, "testbed",
1094                                                "OVERLAY_RANDOM_LINKS",
1095                                                &random_links))
1096     {
1097       /* OVERLAY option RANDOM & SMALL_WORLD_RING requires OVERLAY_RANDOM_LINKS
1098        * option to be set to the number of random links to be established  */
1099       GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, "testbed",
1100                                  "OVERLAY_RANDOM_LINKS");
1101       goto error_cleanup;
1102     }
1103     if (random_links > UINT32_MAX)
1104     {
1105       GNUNET_break (0);         /* Too big number */
1106       goto error_cleanup;
1107     }
1108     rc->random_links = (unsigned int) random_links;
1109     break;
1110   case GNUNET_TESTBED_TOPOLOGY_FROM_FILE:
1111     if (GNUNET_OK !=
1112         GNUNET_CONFIGURATION_get_value_string (rc->cfg, "testbed",
1113                                                "OVERLAY_TOPOLOGY_FILE",
1114                                                &rc->topo_file))
1115     {
1116       GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, "testbed",
1117                                  "OVERLAY_TOPOLOGY_FILE");
1118       goto error_cleanup;
1119     }
1120   default:
1121     /* Warn if OVERLAY_RANDOM_LINKS is present that it will be ignored */
1122     if (GNUNET_YES ==
1123         GNUNET_CONFIGURATION_have_value (rc->cfg, "testbed",
1124                                          "OVERLAY_RANDOM_LINKS"))
1125       LOG (GNUNET_ERROR_TYPE_WARNING,
1126            "Ignoring value of `OVERLAY_RANDOM_LINKS' in given configuration\n");
1127     break;
1128   }
1129   if (NULL != host_filename)
1130   {
1131     rc->hc_handles =
1132         GNUNET_malloc (sizeof (struct GNUNET_TESTBED_HostHabitableCheckHandle *)
1133                        * rc->num_hosts);
1134     for (nhost = 0; nhost < rc->num_hosts; nhost++)
1135     {
1136       if (NULL ==
1137           (rc->hc_handles[nhost] =
1138            GNUNET_TESTBED_is_host_habitable (rc->hosts[nhost], rc->cfg,
1139                                              &host_habitable_cb, rc)))
1140       {
1141         GNUNET_break (0);
1142         for (nhost = 0; nhost < rc->num_hosts; nhost++)
1143           if (NULL != rc->hc_handles[nhost])
1144             GNUNET_TESTBED_is_host_habitable_cancel (rc->hc_handles[nhost]);
1145         GNUNET_free (rc->hc_handles);
1146         rc->hc_handles = NULL;
1147         goto error_cleanup;
1148       }
1149     }
1150   }
1151   else
1152     rc->cproc =
1153         GNUNET_TESTBED_controller_start ("127.0.0.1", rc->h, rc->cfg,
1154                                          &controller_status_cb, rc);
1155   rc->shutdown_run_task =
1156       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_run,
1157                                     rc);
1158   return;
1159
1160 error_cleanup:
1161   if (NULL != rc->h)
1162     GNUNET_TESTBED_host_destroy (rc->h);
1163   if (NULL != rc->hosts)
1164   {
1165     for (hid = 0; hid < rc->num_hosts; hid++)
1166       if (NULL != rc->hosts[hid])
1167         GNUNET_TESTBED_host_destroy (rc->hosts[hid]);
1168     GNUNET_free (rc->hosts);
1169   }
1170   GNUNET_free (rc);
1171 }
1172
1173
1174 /* end of testbed_api_testbed.c */