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