-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_testbed_service.h"
30 #include "testbed_api_peers.h"
31 #include "testbed_api_hosts.h"
32 #include "testbed_api_topology.h"
33
34 /**
35  * Generic loggins shorthand
36  */
37 #define LOG(kind,...)                                           \
38   GNUNET_log_from (kind, "testbed-api-testbed", __VA_ARGS__)
39
40 /**
41  * Opaque handle to an abstract operation to be executed by the testing framework.
42  */
43 struct GNUNET_TESTBED_Testbed
44 {
45   /**
46    * The array of hosts
47    */
48   struct GNUNET_TESTBED_Host **hosts;
49
50   /**
51    * The number of hosts in the hosts array
52    */
53   unsigned int num_hosts;
54
55   /**
56    * The controller handle
57    */
58   struct GNUNET_TESTBED_Controller *c;
59 };
60
61
62 /**
63  * DLL of operations
64  */
65 struct DLLOperation
66 {
67   /**
68    * The testbed operation handle
69    */
70   struct GNUNET_TESTBED_Operation *op;
71
72   /**
73    * Context information for GNUNET_TESTBED_run()
74    */
75   struct RunContext *rc;
76
77   /**
78    * Closure
79    */
80   void *cls;
81
82   /**
83    * The next pointer for DLL
84    */
85   struct DLLOperation *next;
86
87   /**
88    * The prev pointer for DLL
89    */
90   struct DLLOperation *prev;
91 };
92
93
94 /**
95  * States of RunContext
96  */
97 enum State
98 {
99   /**
100    * Initial state
101    */
102   RC_INIT = 0,
103
104   /**
105    * Controllers on given hosts started and linked
106    */
107   RC_LINKED,
108
109   /**
110    * The testbed run is ready and the master callback can be called now. At this
111    * time the peers are all started and if a topology is provided in the
112    * configuration the topology would have been attempted
113    */
114   RC_READY,
115
116   /**
117    * Peers are stopped
118    */
119   RC_PEERS_STOPPED,
120
121   /**
122    * Peers are destroyed
123    */
124   RC_PEERS_DESTROYED
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    * 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    * Host registration task
218    */
219   GNUNET_SCHEDULER_TaskIdentifier register_hosts_task;
220
221   /**
222    * Task to be run while shutting down
223    */
224   GNUNET_SCHEDULER_TaskIdentifier shutdown_run_task;
225
226   /**
227    * The event mask for the controller
228    */
229   uint64_t event_mask;
230
231   /**
232    * State of this context
233    */
234   enum State state;
235
236   /**
237    * The topology which has to be achieved with the peers started in this context
238    */
239   enum GNUNET_TESTBED_TopologyOption topology;
240
241   /**
242    * Number of hosts in the given host file
243    */
244   unsigned int num_hosts;
245
246   /**
247    * Number of registered hosts. Also used as a counter while checking
248    * habitabillity of hosts
249    */
250   unsigned int reg_hosts;
251
252   /**
253    * Current peer count for an operation; Set this to 0 and increment for each
254    * successful operation on a peer
255    */
256   unsigned int peer_count;
257
258   /**
259    * number of peers to start
260    */
261   unsigned int num_peers;
262
263   /**
264    * counter to count overlay connect attempts. This counter includes both
265    * successful and failed overlay connects
266    */
267   unsigned int oc_count;
268
269   /**
270    * Expected overlay connects. Should be zero if no topology is relavant
271    */
272   unsigned int num_oc;
273
274   /**
275    * Number of random links to established
276    */
277   unsigned int random_links;
278   
279 };
280
281
282 /**
283  * Task for starting peers
284  *
285  * @param cls the RunHandle
286  * @param tc the task context from scheduler
287  */
288 static void
289 start_peers_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
290 {
291   struct RunContext *rc = cls;
292   struct DLLOperation *dll_op;
293   unsigned int peer;
294
295   LOG (GNUNET_ERROR_TYPE_DEBUG, "Starting Peers\n");
296   for (peer = 0; peer < rc->num_peers; peer++)
297   {
298     dll_op = GNUNET_malloc (sizeof (struct DLLOperation));
299     dll_op->op = GNUNET_TESTBED_peer_start (NULL, rc->peers[peer], NULL, NULL);
300     dll_op->cls = rc->peers[peer];
301     GNUNET_CONTAINER_DLL_insert_tail (rc->dll_op_head, rc->dll_op_tail, dll_op);
302   }
303   rc->peer_count = 0;
304 }
305
306
307 /**
308  * Functions of this signature are called when a peer has been successfully
309  * created
310  *
311  * @param cls the closure from GNUNET_TESTBED_peer_create()
312  * @param peer the handle for the created peer; NULL on any error during
313  *          creation
314  * @param emsg NULL if peer is not NULL; else MAY contain the error description
315  */
316 static void
317 peer_create_cb (void *cls, struct GNUNET_TESTBED_Peer *peer, const char *emsg)
318 {
319   struct DLLOperation *dll_op = cls;
320   struct RunContext *rc;
321
322   GNUNET_assert (NULL != dll_op);
323   rc = dll_op->rc;
324   GNUNET_assert (NULL != rc);
325   GNUNET_CONTAINER_DLL_remove (rc->dll_op_head, rc->dll_op_tail, dll_op);
326   GNUNET_TESTBED_operation_done (dll_op->op);
327   GNUNET_free (dll_op);
328   if (NULL == peer)
329   {
330     if (NULL != emsg)
331       LOG (GNUNET_ERROR_TYPE_WARNING, "Error while creating a peer: %s\n",
332            emsg);
333     /* FIXME: GNUNET_TESTBED_shutdown_run()? */
334     return;
335   }
336   rc->peers[rc->peer_count] = peer;
337   rc->peer_count++;
338   if (rc->peer_count < rc->num_peers)
339     return;
340   LOG (GNUNET_ERROR_TYPE_DEBUG, "Required peers created successfully\n");
341   GNUNET_SCHEDULER_add_now (&start_peers_task, rc);
342 }
343
344
345 /**
346  * Assuming all peers have been destroyed cleanup run handle
347  *
348  * @param cls the run handle
349  * @param tc the task context from scheduler
350  */
351 static void
352 cleanup_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
353 {
354   struct RunContext *rc = cls;
355   struct DLLOperation *dll_op;
356   unsigned int hid;
357
358   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == rc->register_hosts_task);
359   GNUNET_assert (NULL == rc->reg_handle);
360   GNUNET_assert (NULL == rc->peers);
361   GNUNET_assert (NULL == rc->hc_handles);
362   GNUNET_assert (RC_PEERS_DESTROYED == rc->state);
363   if (NULL != rc->c)
364     GNUNET_TESTBED_controller_disconnect (rc->c);
365   if (NULL != rc->cproc)
366     GNUNET_TESTBED_controller_stop (rc->cproc);
367   if (NULL != rc->h)
368     GNUNET_TESTBED_host_destroy (rc->h);
369   for (hid = 0; hid < rc->num_hosts; hid++)
370         GNUNET_TESTBED_host_destroy (rc->hosts[hid]);
371   GNUNET_free_non_null (rc->hosts);
372   if (NULL != rc->dll_op_head)
373   {
374     LOG (GNUNET_ERROR_TYPE_WARNING,
375          _("Some operations are still pending. Cancelling them\n"));
376     while (NULL != (dll_op = rc->dll_op_head))
377     {
378       GNUNET_TESTBED_operation_done (dll_op->op);
379       GNUNET_CONTAINER_DLL_remove (rc->dll_op_head, rc->dll_op_tail, dll_op);
380       GNUNET_free (dll_op);
381     }
382   }
383   if (NULL != rc->cfg)
384     GNUNET_CONFIGURATION_destroy (rc->cfg);
385   GNUNET_free_non_null (rc->topo_file);
386   GNUNET_free (rc);
387 }
388
389
390 /**
391  * Stops the testbed run and releases any used resources
392  *
393  * @param cls the tesbed run handle
394  * @param tc the task context from scheduler
395  */
396 static void
397 shutdown_run (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
398 {
399   struct RunContext *rc = cls;
400   struct DLLOperation *dll_op;
401   unsigned int peer;
402   unsigned int nhost;
403
404   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != rc->shutdown_run_task);
405   rc->shutdown_run_task = GNUNET_SCHEDULER_NO_TASK;
406   if (NULL != rc->hc_handles)
407   {
408     for (nhost = 0; nhost < rc->num_hosts; nhost++)
409       if (NULL != rc->hc_handles[nhost])
410         GNUNET_TESTBED_is_host_habitable_cancel (rc->hc_handles[nhost]);
411     GNUNET_free (rc->hc_handles);
412     rc->hc_handles = NULL;
413   }
414   /* Stop register hosts task if it is running */
415   if (GNUNET_SCHEDULER_NO_TASK != rc->register_hosts_task)
416   {
417     GNUNET_SCHEDULER_cancel (rc->register_hosts_task);
418     rc->register_hosts_task = GNUNET_SCHEDULER_NO_TASK;
419   }
420   if (NULL != rc->reg_handle)
421   {
422     GNUNET_TESTBED_cancel_registration (rc->reg_handle);
423     rc->reg_handle = NULL;
424   }
425   if (NULL != rc->c)
426   {
427     if (NULL != rc->peers)
428     {
429       if (NULL != rc->topology_operation)
430       {
431         GNUNET_TESTBED_operation_done (rc->topology_operation);
432         rc->topology_operation = NULL;
433       }
434       if (RC_INIT == rc->state)
435         rc->state = RC_READY;   /* Even though we haven't called the master callback */
436       rc->peer_count = 0;
437       /* Check if some peers are stopped */
438       for (peer = 0; peer < rc->num_peers; peer++)
439       {
440         if (PS_STOPPED != rc->peers[peer]->state)
441           break;
442       }
443       if (peer == rc->num_peers)
444       {
445         /* All peers are stopped */
446         rc->state = RC_PEERS_STOPPED;
447         for (peer = 0; peer < rc->num_peers; peer++)
448         {
449           dll_op = GNUNET_malloc (sizeof (struct DLLOperation));
450           dll_op->op = GNUNET_TESTBED_peer_destroy (rc->peers[peer]);
451           GNUNET_CONTAINER_DLL_insert_tail (rc->dll_op_head, rc->dll_op_tail,
452                                             dll_op);
453         }
454         return;
455       }
456       /* Some peers are stopped */
457       for (peer = 0; peer < rc->num_peers; peer++)
458       {
459         if (PS_STARTED != rc->peers[peer]->state)
460         {
461           rc->peer_count++;
462           continue;
463         }
464         dll_op = GNUNET_malloc (sizeof (struct DLLOperation));
465         dll_op->op = GNUNET_TESTBED_peer_stop (rc->peers[peer], NULL, NULL);
466         dll_op->cls = rc->peers[peer];
467         GNUNET_CONTAINER_DLL_insert_tail (rc->dll_op_head, rc->dll_op_tail,
468                                           dll_op);
469       }
470       if (rc->peer_count != rc->num_peers)
471         return;
472     }
473   }
474   rc->state = RC_PEERS_DESTROYED;       /* No peers are present so we consider the
475                                          * state where all peers are destroyed  */
476   GNUNET_SCHEDULER_add_now (&cleanup_task, rc);
477 }
478
479
480 /**
481  * Task to call master task
482  *
483  * @param cls the run context
484  * @param tc the task context
485  */
486 static void
487 call_master (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
488 {
489   struct RunContext *rc = cls;
490   
491   if (NULL != rc->topology_operation)
492   {
493     GNUNET_TESTBED_operation_done (rc->topology_operation);
494     rc->topology_operation = NULL;
495   }
496   if (NULL != rc->test_master)
497     rc->test_master (rc->test_master_cls, rc->num_peers, rc->peers);
498 }
499
500
501 /**
502  * Function to create peers
503  *
504  * @param rc the RunContext
505  */
506 static void
507 create_peers (struct RunContext *rc)
508 {
509   struct DLLOperation *dll_op;
510   unsigned int peer;
511
512   rc->peers =
513       GNUNET_malloc (sizeof (struct GNUNET_TESTBED_Peer *) * rc->num_peers);
514   GNUNET_assert (NULL != rc->c);
515   rc->peer_count = 0;
516   for (peer = 0; peer < rc->num_peers; peer++)
517   {
518     dll_op = GNUNET_malloc (sizeof (struct DLLOperation));
519     dll_op->rc = rc;
520     dll_op->op =
521         GNUNET_TESTBED_peer_create (rc->c, 
522                                     (0 == rc->num_hosts)
523                                     ? rc->h : rc->hosts[peer % rc->num_hosts],
524                                     rc->cfg,
525                                     peer_create_cb, dll_op);
526     GNUNET_CONTAINER_DLL_insert_tail (rc->dll_op_head, rc->dll_op_tail, dll_op);
527   }
528 }
529
530
531 /**
532  * Signature of the event handler function called by the
533  * respective event controller.
534  *
535  * @param cls closure
536  * @param event information about the event
537  */
538 static void
539 event_cb (void *cls, const struct GNUNET_TESTBED_EventInformation *event)
540 {
541   struct RunContext *rc = cls;
542   struct DLLOperation *dll_op;
543   unsigned int peer_id;
544
545   if (RC_INIT == rc->state)
546   {
547     switch (event->type)
548     {
549     case GNUNET_TESTBED_ET_OPERATION_FINISHED:
550       dll_op = event->details.operation_finished.op_cls;
551       if (NULL != event->details.operation_finished.emsg)
552       {
553         LOG (GNUNET_ERROR_TYPE_ERROR,
554              _("Linking controllers failed. Exiting"));
555         GNUNET_SCHEDULER_cancel (rc->shutdown_run_task);
556         rc->shutdown_run_task = GNUNET_SCHEDULER_add_now (&shutdown_run, rc);
557       }
558       else
559         rc->reg_hosts++;
560       GNUNET_assert (event->details.operation_finished.operation == dll_op->op);
561       GNUNET_CONTAINER_DLL_remove (rc->dll_op_head, rc->dll_op_tail, dll_op);
562       GNUNET_TESTBED_operation_done (dll_op->op);
563       GNUNET_free (dll_op);
564       if (rc->reg_hosts == rc->num_hosts)
565       {
566         rc->state = RC_LINKED;
567         create_peers (rc);
568       }
569       return;
570     default:
571       GNUNET_assert (0);
572       GNUNET_SCHEDULER_cancel (rc->shutdown_run_task);
573       rc->shutdown_run_task = GNUNET_SCHEDULER_add_now (&shutdown_run, rc);
574       return;
575     }
576   }
577   if (NULL != rc->topology_operation)
578   {
579     switch (event->type)
580     {
581     case GNUNET_TESTBED_ET_OPERATION_FINISHED:
582     case GNUNET_TESTBED_ET_CONNECT:
583       rc->oc_count++;
584       break;
585     default:
586       GNUNET_assert (0);
587       GNUNET_SCHEDULER_cancel (rc->shutdown_run_task);
588       rc->shutdown_run_task = GNUNET_SCHEDULER_add_now (&shutdown_run, rc);
589       return;
590     }
591     if (rc->oc_count == rc->num_oc)
592     {
593       rc->state = RC_READY;
594       GNUNET_SCHEDULER_add_continuation (&call_master, rc,
595                                          GNUNET_SCHEDULER_REASON_PREREQ_DONE);
596     }
597     return;
598   }
599   if ((RC_LINKED < rc->state) &&
600       ((GNUNET_TESTBED_ET_OPERATION_FINISHED == event->type) ||
601        (GNUNET_TESTBED_ET_PEER_STOP == event->type)))
602   {
603     for (dll_op = rc->dll_op_head; NULL != dll_op; dll_op = dll_op->next)
604     {
605       if ((GNUNET_TESTBED_ET_OPERATION_FINISHED == event->type) &&
606           (event->details.operation_finished.operation == dll_op->op))
607         break;
608       if ((GNUNET_TESTBED_ET_PEER_STOP == event->type) &&
609           (event->details.peer_stop.peer == dll_op->cls))
610         break;
611     }
612     if (NULL == dll_op)
613       goto call_cc;
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     rc->peer_count++;
618     if (rc->peer_count < rc->num_peers)
619       return;
620     switch (rc->state)
621     {
622     case RC_READY:
623       rc->state = RC_PEERS_STOPPED;
624       rc->peer_count = 0;
625       for (peer_id = 0; peer_id < rc->num_peers; peer_id++)
626       {
627         dll_op = GNUNET_malloc (sizeof (struct DLLOperation));
628         dll_op->op = GNUNET_TESTBED_peer_destroy (rc->peers[peer_id]);
629         GNUNET_CONTAINER_DLL_insert_tail (rc->dll_op_head, rc->dll_op_tail,
630                                           dll_op);
631       }
632       break;
633     case RC_PEERS_STOPPED:
634       rc->state = RC_PEERS_DESTROYED;
635       GNUNET_free (rc->peers);
636       rc->peers = NULL;
637       LOG (GNUNET_ERROR_TYPE_DEBUG, "All peers successfully destroyed\n");
638       GNUNET_SCHEDULER_add_now (&cleanup_task, rc);
639       break;
640     default:
641       GNUNET_assert (0);
642     }
643     return;
644   }
645
646 call_cc:
647   if ((0 != (rc->event_mask & (1LL << event->type))) && (NULL != rc->cc))
648     rc->cc (rc->cc_cls, event);
649   if (GNUNET_TESTBED_ET_PEER_START != event->type)
650     return;
651   for (dll_op = rc->dll_op_head; NULL != dll_op; dll_op = dll_op->next)
652     if ((NULL != dll_op->cls) &&
653         (event->details.peer_start.peer == dll_op->cls))
654       break;
655   GNUNET_assert (NULL != dll_op);
656   GNUNET_CONTAINER_DLL_remove (rc->dll_op_head, rc->dll_op_tail, dll_op);
657   GNUNET_TESTBED_operation_done (dll_op->op);
658   GNUNET_free (dll_op);
659   rc->peer_count++;
660   if (rc->peer_count < rc->num_peers)
661     return;
662   LOG (GNUNET_ERROR_TYPE_DEBUG, "Peers started successfully\n");
663   if (GNUNET_TESTBED_TOPOLOGY_NONE != rc->topology)
664   {
665     if ( (GNUNET_TESTBED_TOPOLOGY_ERDOS_RENYI == rc->topology)
666          || (GNUNET_TESTBED_TOPOLOGY_SMALL_WORLD_RING == rc->topology)
667          || (GNUNET_TESTBED_TOPOLOGY_SMALL_WORLD == rc->topology))
668     {
669       rc->topology_operation =
670           GNUNET_TESTBED_overlay_configure_topology (NULL,
671                                                      rc->num_peers,
672                                                      rc->peers,
673                                                      &rc->num_oc,
674                                                      rc->topology,
675                                                      rc->random_links,
676                                                      GNUNET_TESTBED_TOPOLOGY_OPTION_END);
677     }
678     else if (GNUNET_TESTBED_TOPOLOGY_FROM_FILE == rc->topology)
679     {
680       GNUNET_assert (NULL != rc->topo_file);
681       rc->topology_operation =
682           GNUNET_TESTBED_overlay_configure_topology (NULL,
683                                                      rc->num_peers,
684                                                      rc->peers,
685                                                      &rc->num_oc,
686                                                      rc->topology,
687                                                      rc->topo_file,
688                                                      GNUNET_TESTBED_TOPOLOGY_OPTION_END);
689     }
690     else
691       rc->topology_operation =
692           GNUNET_TESTBED_overlay_configure_topology (NULL,
693                                                      rc->num_peers,
694                                                      rc->peers,
695                                                      &rc->num_oc,
696                                                      rc->topology,
697                                                      GNUNET_TESTBED_TOPOLOGY_OPTION_END);
698     if (NULL == rc->topology_operation)
699       LOG (GNUNET_ERROR_TYPE_WARNING,
700            "Not generating topology. Check number of peers\n");
701     else
702       return;
703   }
704   rc->state = RC_READY;
705   GNUNET_SCHEDULER_add_continuation (&call_master, rc,
706                                      GNUNET_SCHEDULER_REASON_PREREQ_DONE);
707 }
708
709
710 /**
711  * Task to register all hosts available in the global host list
712  *
713  * @param cls the RunContext
714  * @param tc the scheduler task context
715  */
716 static void
717 register_hosts (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
718
719
720 /**
721  * Callback which will be called to after a host registration succeeded or failed
722  *
723  * @param cls the closure
724  * @param emsg the error message; NULL if host registration is successful
725  */
726 static void
727 host_registration_completion (void *cls, const char *emsg)
728 {
729   struct RunContext *rc = cls;
730
731   rc->reg_handle = NULL;
732   if (NULL != emsg)
733   {
734     LOG (GNUNET_ERROR_TYPE_WARNING,
735          _("Host registration failed for a host. Error: %s\n"), emsg);
736     GNUNET_SCHEDULER_cancel (rc->shutdown_run_task);
737     rc->shutdown_run_task = GNUNET_SCHEDULER_add_now (&shutdown_run, rc);
738     return;
739   }
740   rc->register_hosts_task = GNUNET_SCHEDULER_add_now (&register_hosts, rc);
741 }
742
743
744 /**
745  * Task to register all hosts available in the global host list
746  *
747  * @param cls RunContext
748  * @param tc the scheduler task context
749  */
750 static void
751 register_hosts (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
752 {
753   struct RunContext *rc = cls;
754   struct DLLOperation *dll_op;
755   unsigned int slave;
756
757   rc->register_hosts_task = GNUNET_SCHEDULER_NO_TASK;
758   if (rc->reg_hosts == rc->num_hosts)
759   {
760     LOG (GNUNET_ERROR_TYPE_DEBUG,
761          "All hosts successfully registered\n");
762     /* Start slaves */
763     for (slave = 0; slave < rc->num_hosts; slave++)
764     {
765       dll_op = GNUNET_malloc (sizeof (struct DLLOperation));
766       dll_op->rc = rc;
767       dll_op->op = GNUNET_TESTBED_controller_link (dll_op,
768                                                    rc->c,
769                                                    rc->hosts[slave],
770                                                    rc->h,
771                                                    rc->cfg,
772                                                    GNUNET_YES);
773       GNUNET_CONTAINER_DLL_insert_tail (rc->dll_op_head, rc->dll_op_tail, dll_op);
774     }
775     rc->reg_hosts = 0;
776     return;
777   }
778   rc->reg_handle = GNUNET_TESTBED_register_host (rc->c,
779                                                  rc->hosts[rc->reg_hosts++],
780                                                  host_registration_completion,
781                                                  rc);
782 }
783
784
785 /**
786  * Callback to signal successfull startup of the controller process
787  *
788  * @param cls the closure from GNUNET_TESTBED_controller_start()
789  * @param cfg the configuration with which the controller has been started;
790  *          NULL if status is not GNUNET_OK
791  * @param status GNUNET_OK if the startup is successfull; GNUNET_SYSERR if not,
792  *          GNUNET_TESTBED_controller_stop() shouldn't be called in this case
793  */
794 static void
795 controller_status_cb (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg,
796                       int status)
797 {
798   struct RunContext *rc = cls;
799   uint64_t event_mask;
800
801   if (status != GNUNET_OK)
802   {
803     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Testbed startup failed\n");
804     return;
805   }
806   GNUNET_CONFIGURATION_destroy (rc->cfg);
807   rc->cfg = GNUNET_CONFIGURATION_dup (cfg);
808   event_mask = rc->event_mask;
809   event_mask |= (1LL << GNUNET_TESTBED_ET_PEER_STOP);
810   event_mask |= (1LL << GNUNET_TESTBED_ET_OPERATION_FINISHED);
811   event_mask |= (1LL << GNUNET_TESTBED_ET_PEER_START);
812   if (rc->topology < GNUNET_TESTBED_TOPOLOGY_NONE)
813     event_mask |= GNUNET_TESTBED_ET_CONNECT;
814   rc->c =
815       GNUNET_TESTBED_controller_connect (rc->cfg, rc->h, event_mask, &event_cb, rc);
816   if (0 < rc->num_hosts)
817   {
818     rc->register_hosts_task = GNUNET_SCHEDULER_add_now (&register_hosts, rc);
819     return;
820   }
821   rc->state = RC_LINKED;
822   create_peers (rc);
823 }
824
825
826 /**
827  * Callbacks of this type are called by GNUNET_TESTBED_is_host_habitable to
828  * inform whether the given host is habitable or not. The Handle returned by
829  * GNUNET_TESTBED_is_host_habitable() is invalid after this callback is called
830  *
831  * @param cls NULL
832  * @param host the host whose status is being reported; will be NULL if the host
833  *          given to GNUNET_TESTBED_is_host_habitable() is NULL
834  * @param status GNUNET_YES if it is habitable; GNUNET_NO if not
835  */
836 static void 
837 host_habitable_cb (void *cls, const struct GNUNET_TESTBED_Host *host, int status)
838 {
839   struct RunContext *rc = cls;
840   unsigned int nhost;
841   
842   for (nhost = 0; nhost < rc->num_hosts; nhost++)
843   {
844     if (host == rc->hosts[nhost])
845       break;
846   }
847   GNUNET_assert (nhost != rc->num_hosts);
848   rc->hc_handles[nhost] = NULL;
849   if (GNUNET_NO == status)
850   {
851     if ((NULL != host) && (NULL != GNUNET_TESTBED_host_get_hostname (host)))
852       LOG (GNUNET_ERROR_TYPE_ERROR, _("Host %s cannot start testbed\n"),
853            GNUNET_TESTBED_host_get_hostname (host));
854     else
855       LOG (GNUNET_ERROR_TYPE_ERROR, _("Testbed cannot be started on localhost\n"));
856     GNUNET_SCHEDULER_cancel (rc->shutdown_run_task);
857     rc->shutdown_run_task = GNUNET_SCHEDULER_add_now (&shutdown_run, rc);
858     return;
859   }
860   rc->reg_hosts++;
861   if (rc->reg_hosts < rc->num_hosts)
862     return;
863   GNUNET_free (rc->hc_handles);
864   rc->hc_handles = NULL;
865   rc->h = rc->hosts[0];
866   rc->num_hosts--;
867   if (0 < rc->num_hosts)
868     rc->hosts = &rc->hosts[1];
869   else
870   {
871     GNUNET_free (rc->hosts);
872     rc->hosts = NULL;
873   }
874   /* FIXME: If we are starting controller on different host 127.0.0.1 may not ab
875   correct */
876   rc->cproc =
877       GNUNET_TESTBED_controller_start ("127.0.0.1", rc->h, rc->cfg,
878                                        &controller_status_cb, rc);
879   if (NULL == rc->cproc)
880   {
881     LOG (GNUNET_ERROR_TYPE_ERROR, _("Cannot start the master controller"));
882     GNUNET_SCHEDULER_cancel (rc->shutdown_run_task);
883     rc->shutdown_run_task = GNUNET_SCHEDULER_add_now (&shutdown_run, rc);
884   }
885 }
886
887
888 /**
889  * Convenience method for running a testbed with
890  * a single call.  Underlay and overlay topology
891  * are configured using the "UNDERLAY" and "OVERLAY"
892  * options in the "[testbed]" section of the configuration\
893  * (with possible options given in "UNDERLAY_XXX" and/or
894  * "OVERLAY_XXX").
895  *
896  * The testbed is to be terminated using a call to
897  * "GNUNET_SCHEDULER_shutdown".
898  *
899  * @param host_filename name of the file with the 'hosts', NULL
900  *        to run everything on 'localhost'
901  * @param cfg configuration to use (for testbed, controller and peers)
902  * @param num_peers number of peers to start; FIXME: maybe put that ALSO into cfg?
903  * @param event_mask bit mask with set of events to call 'cc' for;
904  *                   or-ed values of "1LL" shifted by the
905  *                   respective 'enum GNUNET_TESTBED_EventType'
906  *                   (i.e.  "(1LL << GNUNET_TESTBED_ET_CONNECT) || ...")
907  * @param cc controller callback to invoke on events; This callback is called
908  *          for all peer start events even if GNUNET_TESTBED_ET_PEER_START isn't
909  *          set in the event_mask as this is the only way get access to the
910  *          handle of each peer
911  * @param cc_cls closure for cc
912  * @param test_master this callback will be called once the test is ready
913  * @param test_master_cls closure for 'test_master'.
914  */
915 void
916 GNUNET_TESTBED_run (const char *host_filename,
917                     const struct GNUNET_CONFIGURATION_Handle *cfg,
918                     unsigned int num_peers, uint64_t event_mask,
919                     GNUNET_TESTBED_ControllerCallback cc, void *cc_cls,
920                     GNUNET_TESTBED_TestMaster test_master,
921                     void *test_master_cls)
922 {
923   struct RunContext *rc;
924   char *topology;
925   unsigned long long random_links;
926   unsigned int hid;
927   unsigned int nhost;
928   
929   GNUNET_assert (num_peers > 0);
930   rc = GNUNET_malloc (sizeof (struct RunContext));
931   if (NULL != host_filename)
932   {
933     rc->num_hosts =
934         GNUNET_TESTBED_hosts_load_from_file (host_filename, &rc->hosts);
935     if (0 == rc->num_hosts)
936     {
937       LOG (GNUNET_ERROR_TYPE_WARNING,
938            _("No hosts loaded. Need at least one host\n"));
939       goto error_cleanup;
940     }
941   }
942   else
943     rc->h = GNUNET_TESTBED_host_create (NULL, NULL, 0);
944   rc->cfg = GNUNET_CONFIGURATION_dup (cfg);
945   rc->num_peers = num_peers;
946   rc->event_mask = event_mask;
947   rc->cc = cc;
948   rc->cc_cls = cc_cls;
949   rc->test_master = test_master;
950   rc->test_master_cls = test_master_cls;
951   rc->state = RC_INIT;
952   rc->topology = GNUNET_TESTBED_TOPOLOGY_NONE;  
953   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (rc->cfg, "testbed",
954                                                           "OVERLAY_TOPOLOGY",
955                                                           &topology))
956   {
957     if (GNUNET_NO == GNUNET_TESTBED_topology_get_ (&rc->topology,
958                                                     topology))
959     {
960       LOG (GNUNET_ERROR_TYPE_WARNING,
961            "Unknown topology %s given in configuration\n", topology);
962     }
963     GNUNET_free (topology);
964   }
965   switch (rc->topology)
966   {
967   case GNUNET_TESTBED_TOPOLOGY_ERDOS_RENYI:
968   case GNUNET_TESTBED_TOPOLOGY_SMALL_WORLD_RING:
969   case GNUNET_TESTBED_TOPOLOGY_SMALL_WORLD:
970     if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (rc->cfg, "testbed",
971                                                             "OVERLAY_RANDOM_LINKS",
972                                                             &random_links))
973     {
974       /* OVERLAY option RANDOM & SMALL_WORLD_RING requires OVERLAY_RANDOM_LINKS
975          option to be set to the number of random links to be established  */
976       GNUNET_break (0);
977       goto error_cleanup;
978     }
979     if (random_links > UINT32_MAX)
980     {
981       GNUNET_break (0);       /* Too big number */
982       goto error_cleanup;
983     }
984     rc->random_links = (unsigned int) random_links;
985     break;
986   case GNUNET_TESTBED_TOPOLOGY_FROM_FILE:
987     if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (rc->cfg, "testbed",
988                                                             "TOPOLOGY_FILE",
989                                                             &rc->topo_file))
990     {
991       /* You need to set TOPOLOGY_FILE option to a topolog file */
992       GNUNET_break (0);
993       goto error_cleanup;
994     }
995     break;
996   default:   
997     /* Do nothing */
998     break;
999   }
1000   if (NULL != host_filename)
1001   {
1002     rc->hc_handles = GNUNET_malloc (sizeof (struct
1003                                             GNUNET_TESTBED_HostHabitableCheckHandle *) 
1004                                     * rc->num_hosts);
1005     for (nhost = 0; nhost < rc->num_hosts; nhost++) 
1006     {    
1007       if (NULL == (rc->hc_handles[nhost] = 
1008                    GNUNET_TESTBED_is_host_habitable (rc->hosts[nhost], rc->cfg,
1009                                                      &host_habitable_cb,
1010                                                      rc)))
1011       {
1012         GNUNET_break (0);
1013         for (nhost = 0; nhost < rc->num_hosts; nhost++)
1014           if (NULL != rc->hc_handles[nhost])
1015             GNUNET_TESTBED_is_host_habitable_cancel (rc->hc_handles[nhost]);
1016         GNUNET_free (rc->hc_handles);
1017         rc->hc_handles = NULL;
1018         goto error_cleanup;
1019       }
1020     }
1021   }
1022   else
1023     rc->cproc =
1024       GNUNET_TESTBED_controller_start ("127.0.0.1", rc->h, rc->cfg,
1025                                        &controller_status_cb, rc);
1026   rc->shutdown_run_task =
1027       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1028                                     &shutdown_run, rc);
1029   return;
1030
1031  error_cleanup:
1032   if (NULL != rc->h)
1033     GNUNET_TESTBED_host_destroy (rc->h);
1034   if (NULL != rc->hosts)
1035   {
1036     for (hid = 0; hid < rc->num_hosts; hid++)
1037       if (NULL != rc->hosts[hid])
1038         GNUNET_TESTBED_host_destroy (rc->hosts[hid]);
1039     GNUNET_free (rc->hosts);
1040   }
1041   GNUNET_free (rc);
1042 }
1043
1044
1045 /**
1046  * Configure and run a testbed using the given
1047  * master controller on 'num_hosts' starting
1048  * 'num_peers' using the given peer configuration.
1049  *
1050  * @param controller master controller for the testbed
1051  *                   (must not be destroyed until after the
1052  *                    testbed is destroyed).
1053  * @param num_hosts number of hosts in 'hosts', 0 to only
1054  *        use 'localhost'
1055  * @param hosts list of hosts to use for the testbed
1056  * @param num_peers number of peers to start
1057  * @param cfg the configuration to use as a template for peers and also for
1058  *         checking the value of testbed helper binary
1059  * @param underlay_topology underlay topology to create
1060  * @param va topology-specific options
1061  * @return handle to the testbed; NULL upon error (error messaage will be printed)
1062  */
1063 struct GNUNET_TESTBED_Testbed *
1064 GNUNET_TESTBED_create_va (struct GNUNET_TESTBED_Controller *controller,
1065                           unsigned int num_hosts,
1066                           struct GNUNET_TESTBED_Host **hosts,
1067                           unsigned int num_peers,
1068                           const struct GNUNET_CONFIGURATION_Handle *cfg,
1069                           enum GNUNET_TESTBED_TopologyOption underlay_topology,
1070                           va_list va)
1071 {
1072   /* unsigned int nhost; */
1073
1074   /* GNUNET_assert (underlay_topology < GNUNET_TESTBED_TOPOLOGY_NONE); */
1075   /* if (num_hosts != 0) */
1076   /* { */
1077   /*   for (nhost = 0; nhost < num_hosts; nhost++) */
1078   /*   { */
1079   /*     if (GNUNET_YES != GNUNET_TESTBED_is_host_habitable (hosts[nhost], cfg)) */
1080   /*     { */
1081   /*       LOG (GNUNET_ERROR_TYPE_ERROR, _("Host %s cannot start testbed\n"), */
1082   /*            GNUNET_TESTBED_host_get_hostname_ (hosts[nhost])); */
1083   /*       break; */
1084   /*     } */
1085   /*   } */
1086   /*   if (num_hosts != nhost) */
1087   /*     return NULL; */
1088   /* } */
1089   /* We need controller callback here to get operation done events while
1090      linking hosts */
1091   GNUNET_break (0);
1092   return NULL;
1093 }
1094
1095
1096 /**
1097  * Configure and run a testbed using the given
1098  * master controller on 'num_hosts' starting
1099  * 'num_peers' using the given peer configuration.
1100  *
1101  * @param controller master controller for the testbed
1102  *                   (must not be destroyed until after the
1103  *                    testbed is destroyed).
1104  * @param num_hosts number of hosts in 'hosts', 0 to only
1105  *        use 'localhost'
1106  * @param hosts list of hosts to use for the testbed
1107  * @param num_peers number of peers to start
1108  * @param cfg the configuration to use as a template for peers and also for
1109  *         checking the value of testbed helper binary
1110  * @param underlay_topology underlay topology to create
1111  * @param ... topology-specific options
1112  */
1113 struct GNUNET_TESTBED_Testbed *
1114 GNUNET_TESTBED_create (struct GNUNET_TESTBED_Controller *controller,
1115                        unsigned int num_hosts,
1116                        struct GNUNET_TESTBED_Host **hosts,
1117                        unsigned int num_peers,
1118                        const struct GNUNET_CONFIGURATION_Handle *cfg,
1119                        enum GNUNET_TESTBED_TopologyOption underlay_topology,
1120                        ...)
1121 {
1122   struct GNUNET_TESTBED_Testbed *testbed;
1123   va_list vargs;
1124   
1125   va_start (vargs, underlay_topology);
1126   testbed = GNUNET_TESTBED_create_va (controller, num_hosts, hosts, num_peers,
1127                                       cfg, underlay_topology, vargs);
1128   va_end (vargs);
1129   return testbed;
1130 }
1131
1132
1133 /**
1134  * Destroy a testbed.  Stops all running peers and then
1135  * destroys all peers.  Does NOT destroy the master controller.
1136  *
1137  * @param testbed testbed to destroy
1138  */
1139 void
1140 GNUNET_TESTBED_destroy (struct GNUNET_TESTBED_Testbed *testbed)
1141 {
1142   GNUNET_break (0);
1143 }
1144
1145
1146 /* end of testbed_api_testbed.c */