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