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