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