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