- More documentation
[oweals/gnunet.git] / src / nse / gnunet-nse-profiler.c
1 /*
2      This file is part of GNUnet.
3      (C) 2011, 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  * @file nse/gnunet-nse-profiler.c
22  *
23  * @brief Profiling driver for the network size estimation service.
24  *        Generally, the profiler starts a given number of peers,
25  *        then churns some off, waits a certain amount of time, then
26  *        churns again, and repeats.
27  *
28  * TODO:
29  * - need to enable user to specify topology options
30  * - need to check for leaks (especially FD leaks)
31  * - need to TEST
32  */
33 #include "platform.h"
34 #include "gnunet_testbed_service.h"
35 #include "gnunet_nse_service.h"
36
37
38 /**
39  * Information we track for a peer in the testbed.
40  */
41 struct NSEPeer
42 {
43   /**
44    * Prev reference in DLL.
45    */
46   struct NSEPeer *prev;
47
48   /**
49    * Next reference in DLL.
50    */
51   struct NSEPeer *next;
52
53   /**
54    * Handle with testbed.
55    */
56   struct GNUNET_TESTBED_Peer *daemon;
57
58   /**
59    * Testbed operation to connect to NSE service.
60    */
61   struct GNUNET_TESTBED_Operation *nse_op;
62
63   /**
64    * Handle to statistics service of the peer.
65    */
66   struct GNUNET_STATISTICS_Handle *stats;
67
68   /**
69    * Testbed operation to connect to statistics service.
70    */
71   struct GNUNET_TESTBED_Operation *stats_op;
72   
73   /**
74    * Task scheduled to get statistics from this peer.
75    */
76   GNUNET_SCHEDULER_TaskIdentifier stats_task;
77 };
78
79
80 /**
81  * Context for the stats task?
82  */
83 struct StatsContext
84 {
85
86   /**
87    * How many messages have peers received during the test.
88    */
89   unsigned long long total_nse_received_messages;
90
91   /**
92    * How many messages have peers send during the test (should be == received).
93    */
94   unsigned long long total_nse_transmitted_messages;
95
96   /**
97    * How many messages have travelled an edge in both directions.
98    */
99   unsigned long long total_nse_cross;
100
101   /**
102    * How many extra messages per edge (corrections) have been received.
103    */
104   unsigned long long total_nse_extra;
105
106   /**
107    * How many messages have been discarded.
108    */
109   unsigned long long total_discarded;
110 };
111
112
113 /**
114  * Head of DLL of peers we monitor closely.
115  */
116 static struct NSEPeer *peer_head;
117
118 /**
119  * Tail of DLL of peers we monitor closely.
120  */
121 static struct NSEPeer *peer_tail;
122
123 /**
124  * Return value from 'main' (0 == success)
125  */
126 static int ok;
127
128 /**
129  * Be verbose (configuration option)
130  */
131 static int verbose;
132
133 /**
134  * Name of the file with the hosts to run the test over (configuration option)
135  */ 
136 static char *hosts_file;
137
138 /**
139  * IP address of this system, as seen by the rest of the system (configuration option)
140  */
141 static char *controller_ip;
142
143 /**
144  * Maximum number of peers in the test.
145  */
146 static unsigned int num_peers;
147
148 /**
149  * Total number of rounds to execute.
150  */
151 static unsigned int num_rounds;
152
153 /**
154  * Current round we are in.
155  */
156 static unsigned int current_round;
157
158 /**
159  * Array of size 'num_rounds' with the requested number of peers in the given round.
160  */
161 static unsigned int *num_peers_in_round;
162
163 /**
164  * How many peers are running right now?
165  */
166 static unsigned int peers_running;
167
168 /**
169  * Specification for the numbers of peers to have in each round.
170  */
171 static char *num_peer_spec;
172
173 /**
174  * Handles to all of the running peers.
175  */
176 static struct GNUNET_TESTBED_Peer **daemons;
177
178 /**
179  * Global configuration file
180  */
181 static struct GNUNET_CONFIGURATION_Handle *testing_cfg;
182
183 /**
184  * Maximum number of connections to NSE services.
185  */
186 static unsigned int connection_limit;
187
188 /**
189  * Total number of connections in the whole network.
190  */
191 static unsigned int total_connections;
192
193 /**
194  * File to report results to.
195  */
196 static struct GNUNET_DISK_FileHandle *output_file;
197
198 /**
199  * Filename to log results to.
200  */
201 static char *output_filename;
202
203 /**
204  * File to log connection info, statistics to.
205  */
206 static struct GNUNET_DISK_FileHandle *data_file;
207
208 /**
209  * Filename to log connection info, statistics to.
210  */
211 static char *data_filename;
212
213 /**
214  * How long to wait before triggering next round?
215  * Default: 60 s.
216  */
217 static struct GNUNET_TIME_Relative wait_time = { 60 * 1000 };
218
219 /**
220  * How often do we query for statistics during a round?
221  * Default: 1 s.
222  */
223 static struct GNUNET_TIME_Relative interval = { 1000 };
224
225 /**
226  * Name of the file where we write the topology for each round; NULL for
227  * none.
228  */
229 static char *topology_file;
230
231 /**
232  * List of hosts we use for the testbed.
233  */
234 static struct GNUNET_TESTBED_Host **hosts;
235
236 /**
237  * Size of the 'hosts' array.
238  */
239 static unsigned int num_hosts;
240
241 /**
242  * Handle to the master controller.
243  */
244 static struct GNUNET_TESTBED_Controller *controller;
245
246 /**
247  * Controller start handle.
248  */
249 static struct GNUNET_TESTBED_ControllerProc *copro;
250
251 /**
252  * Testbed handle.
253  */
254 static struct GNUNET_TESTBED_Testbed *testbed;
255
256
257 /**
258  * Clean up all of the monitoring connections to NSE and
259  * STATISTICS that we keep to selected peers.
260  */
261 static void
262 close_monitor_connections ()
263 {
264   struct NSEPeer *pos;
265
266   while (NULL != (pos = peer_head))
267   {
268     if (NULL != pos->nse_op)
269       GNUNET_TESTBED_operation_done (pos->nse_op);
270     if (NULL != pos->stats_op)
271       GNUNET_TESTBED_operation_done (pos->stats_op);
272     GNUNET_CONTAINER_DLL_remove (peer_head, peer_tail, pos);
273     if (GNUNET_SCHEDULER_NO_TASK != pos->stats_task)
274       GNUNET_SCHEDULER_cancel (pos->stats_task);
275     GNUNET_free (pos);
276   }
277 }
278
279
280 /**
281  * Task run on shutdown; cleans up everything.
282  *
283  * @param cls unused
284  * @param tc unused
285  */
286 static void
287 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
288 {
289   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Ending test.\n");    
290   close_monitor_connections ();
291   if (NULL != testbed)
292     GNUNET_TESTBED_destroy (testbed);
293   if (NULL != controller)
294     GNUNET_TESTBED_controller_disconnect (controller);
295   if (NULL != copro)
296       GNUNET_TESTBED_controller_stop (copro);
297   while (0 > num_hosts)
298     GNUNET_TESTBED_host_destroy (hosts[--num_hosts]);
299   // FIXME: what about closing other files!?
300   if (NULL != data_file)
301     GNUNET_DISK_file_close (data_file);
302 }
303
304
305 /**
306  * Callback to call when network size estimate is updated.
307  *
308  * @param cls closure with the 'struct NSEPeer' providing the update
309  * @param timestamp server timestamp
310  * @param estimate the value of the current network size estimate
311  * @param std_dev standard deviation (rounded down to nearest integer)
312  *                of the size estimation values seen
313  *
314  */
315 static void
316 handle_estimate (void *cls, 
317                  struct GNUNET_TIME_Absolute timestamp,
318                  double estimate, double std_dev)
319 {
320   struct NSEPeer *peer = cls;
321   char output_buffer[512];
322   size_t size;
323
324   if (NULL == output_file)
325     {
326       FPRINTF (stderr,
327                "Received network size estimate from peer %p. Size: %f std.dev. %f\n",
328                peer, estimate, std_dev);
329       return;
330     }
331   size = GNUNET_snprintf (output_buffer, 
332                           sizeof (output_buffer),
333                           "%p %llu %llu %f %f %f\n",
334                           peer, peers_running,
335                           timestamp.abs_value,
336                           GNUNET_NSE_log_estimate_to_n (estimate), estimate,
337                           std_dev);
338   if (size != GNUNET_DISK_file_write (output_file, output_buffer, size))
339     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
340                 "Unable to write to file!\n");
341 }
342
343
344 /**
345  * Process core statistic values.
346  *
347  * @param cls closure
348  * @param subsystem name of subsystem that created the statistic
349  * @param name the name of the datum
350  * @param value the current value
351  * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
352  * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
353  */
354 static int
355 core_stats_iterator (void *cls, const char *subsystem, const char *name,
356                      uint64_t value, int is_persistent)
357 {
358   struct NSEPeer *peer = cls;
359   char output_buffer[512];
360   size_t size;
361
362   if (NULL == output_file)
363     {
364       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
365                   "%p -> %s [%s]: %llu\n",
366                   peer, subsystem, name, value);
367       return GNUNET_OK;
368     }
369   size =
370     GNUNET_snprintf (output_buffer,
371                      sizeof (output_buffer),
372                      "%p [%s] %s %llu\n",
373                      peer,
374                      subsystem, name, value);
375   if (size != GNUNET_DISK_file_write (output_file, output_buffer, size))
376     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Unable to write to file!\n");
377   return GNUNET_OK;
378 }
379
380
381 /**
382  * Continuation called by "get_stats" function once we are done.
383  *
384  * @param cls closure
385  * @param success GNUNET_OK if statistics were
386  *        successfully obtained, GNUNET_SYSERR if not.
387  */
388 static void
389 core_stats_cont (void *cls, int success);
390
391
392 /**
393  * Function invoked periodically to get the statistics.
394  *
395  * @param cls 'struct NSEPeer' to get stats from
396  * @param tc scheduler context
397  */
398 static void
399 core_get_stats (void *cls,
400                 const struct GNUNET_SCHEDULER_TaskContext *tc)
401 {
402   struct NSEPeer *peer = cls;
403
404   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
405   {
406     GNUNET_TESTBED_operation_done (peer->stats_op);
407     peer->stats = NULL;
408     peer->stats_op = NULL;
409     return;
410   }
411   /* FIXME: code duplication! */
412   GNUNET_STATISTICS_get (peer->stats, "core", NULL,
413                          GNUNET_TIME_UNIT_FOREVER_REL,
414                          &core_stats_cont, 
415                          &core_stats_iterator, peer);
416   GNUNET_STATISTICS_get (peer->stats, "transport", NULL,
417                          GNUNET_TIME_UNIT_FOREVER_REL,
418                          NULL,
419                          &core_stats_iterator, peer);
420   GNUNET_STATISTICS_get (peer->stats, "nse", NULL,
421                          GNUNET_TIME_UNIT_FOREVER_REL,
422                          NULL, 
423                          &core_stats_iterator, peer);
424   peer->stats_task = GNUNET_SCHEDULER_NO_TASK;
425 }
426
427
428 /**
429  * Continuation called by "get_stats" function.
430  *
431  * @param cls closure
432  * @param success GNUNET_OK if statistics were
433  *        successfully obtained, GNUNET_SYSERR if not.
434  */
435 static void
436 core_stats_cont (void *cls, 
437                  int success)
438 {
439   struct NSEPeer *peer = cls;
440
441   if (GNUNET_OK != success)
442     return;
443   peer->stats_task = GNUNET_SCHEDULER_add_delayed (interval,
444                                                    &core_get_stats, peer);
445 }
446
447
448 /**
449  * Adapter function called to establish a connection to
450  * statistics service.
451  * 
452  * @param cls closure
453  * @param cfg configuration of the peer to connect to; will be available until
454  *          GNUNET_TESTBED_operation_done() is called on the operation returned
455  *          from GNUNET_TESTBED_service_connect()
456  * @return service handle to return in 'op_result', NULL on error
457  */
458 static void *
459 statistics_connect_adapter (void *cls,
460                             const struct GNUNET_CONFIGURATION_Handle *cfg)
461 {
462   return GNUNET_STATISTICS_create ("<driver>",
463                                    cfg);
464 }
465
466
467 /**
468  * Adapter function called to destroy a connection to
469  * statistics service.
470  * 
471  * @param cls closure
472  * @param op_result service handle returned from the connect adapter
473  */
474 static void 
475 statistics_disconnect_adapter (void *cls,
476                                void *op_result)
477 {
478   GNUNET_STATISTICS_destroy (op_result, GNUNET_NO);
479 }
480
481
482 /**
483  * Function called by testbed once we are connected to stats service.
484  *
485  * @param cls the 'struct NSEPeer' for which we connected to stats
486  * @param op connect operation handle
487  * @param ca_result handle to stats service
488  * @param emsg error message on failure
489  */
490 static void
491 stat_run (void *cls, 
492           struct GNUNET_TESTBED_Operation *op,
493           void *ca_result,
494           const char *emsg)
495 {
496   struct NSEPeer *current_peer = cls;
497
498   if (NULL == ca_result)
499     {
500       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
501                   "Failed to connect to statistics service: %s\n",
502                   emsg);
503       GNUNET_SCHEDULER_shutdown ();
504       return;
505     }
506   current_peer->stats = ca_result;
507   GNUNET_STATISTICS_get (current_peer->stats, "core", NULL,
508                          GNUNET_TIME_UNIT_FOREVER_REL,
509                          &core_stats_cont, 
510                          &core_stats_iterator, current_peer);
511   GNUNET_STATISTICS_get (current_peer->stats, "transport", NULL,
512                          GNUNET_TIME_UNIT_FOREVER_REL,
513                          NULL, 
514                          &core_stats_iterator, current_peer);
515   GNUNET_STATISTICS_get (current_peer->stats, "nse", NULL,
516                          GNUNET_TIME_UNIT_FOREVER_REL,
517                          NULL, 
518                          &core_stats_iterator, current_peer);
519 }
520
521
522 /**
523  * Adapter function called to establish a connection to
524  * NSE service.
525  * 
526  * @param cls closure (the 'struct NSEPeer')
527  * @param cfg configuration of the peer to connect to; will be available until
528  *          GNUNET_TESTBED_operation_done() is called on the operation returned
529  *          from GNUNET_TESTBED_service_connect()
530  * @return service handle to return in 'op_result', NULL on error
531  */
532 static void *
533 nse_connect_adapter (void *cls,
534                      const struct GNUNET_CONFIGURATION_Handle *cfg)
535 {
536   struct NSEPeer *current_peer = cls;
537
538   return GNUNET_NSE_connect (cfg, &handle_estimate, current_peer);
539 }
540
541
542 /**
543  * Adapter function called to destroy a connection to
544  * NSE service.
545  * 
546  * @param cls closure
547  * @param op_result service handle returned from the connect adapter
548  */
549 static void 
550 nse_disconnect_adapter (void *cls,
551                         void *op_result)
552 {
553   GNUNET_NSE_disconnect (op_result);
554 }
555
556
557 /**
558  * Task run to connect to the NSE and statistics services to a subset of
559  * all of the running peers.
560  *
561  * @param cls handle the peer
562  * @param tc ignored
563  */
564 static void
565 connect_nse_service ()
566 {
567   struct NSEPeer *current_peer;
568   unsigned int i;
569
570   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connecting to nse service of peers\n");
571   for (i = 0; i < num_peers; i++)
572   {
573     if ((connection_limit > 0) &&
574         (num_peers > connection_limit) && 
575         (0 != (i % (num_peers / connection_limit))))
576       continue;
577     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
578                 "nse-profiler: connecting to nse service of peer %d\n", i);
579     current_peer = GNUNET_malloc (sizeof (struct NSEPeer));
580     current_peer->daemon = daemons[i];
581     current_peer->nse_op 
582       = GNUNET_TESTBED_service_connect (NULL,
583                                         current_peer->daemon,
584                                         "nse",
585                                         NULL, NULL,
586                                         &nse_connect_adapter,
587                                         &nse_disconnect_adapter,
588                                         current_peer);  
589     current_peer->stats_op 
590       = GNUNET_TESTBED_service_connect (NULL,
591                                         current_peer->daemon,
592                                         "statistics",
593                                         &stat_run, current_peer,
594                                         &statistics_connect_adapter,
595                                         &statistics_disconnect_adapter,
596                                         NULL);  
597     GNUNET_CONTAINER_DLL_insert (peer_head, peer_tail, current_peer);
598   }
599 }
600
601
602 /**
603  * Task that starts/stops peers to move to the next round.
604  *
605  * @param cls NULL, unused
606  * @param tc scheduler context (unused)
607  */
608 static void
609 next_round (void *cls, 
610             const struct GNUNET_SCHEDULER_TaskContext *tc);
611
612
613 /**
614  * Continuation called by the "get_all" and "get" functions at the
615  * end of a round.  Obtains the final statistics and writes them to
616  * the file, then either starts the next round, or, if this was the
617  * last round, terminates the run.
618  *
619  * @param cls struct StatsContext
620  * @param success GNUNET_OK if statistics were
621  *        successfully obtained, GNUNET_SYSERR if not.
622  */
623 static void
624 stats_finished_callback (void *cls,
625                          struct GNUNET_TESTBED_Operation *op,
626                          const char *emsg)
627 {
628   struct StatsContext *stats_context = cls;
629   char buf[512];
630   size_t buf_len;
631
632   if (NULL != emsg)
633     {
634       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
635                   "Failed to get statistics: %s\n",
636                   emsg);
637       GNUNET_SCHEDULER_shutdown ();
638       GNUNET_free (stats_context);
639       return;
640     }
641   if (NULL != data_file)
642     {
643       /* Stats lookup successful, write out data */
644       buf_len =
645         GNUNET_snprintf (buf, sizeof (buf),
646                          "TOTAL_NSE_RECEIVED_MESSAGES_%u: %u \n",
647                          current_round,
648                          stats_context->total_nse_received_messages);
649       GNUNET_DISK_file_write (data_file, buf, buf_len);
650       buf_len =
651         GNUNET_snprintf (buf, sizeof (buf),
652                          "TOTAL_NSE_TRANSMITTED_MESSAGES_%u: %u\n",
653                          current_round,
654                          stats_context->total_nse_transmitted_messages);
655       GNUNET_DISK_file_write (data_file, buf, buf_len);    
656       buf_len =
657         GNUNET_snprintf (buf, sizeof (buf),
658                          "TOTAL_NSE_CROSS_%u: %u \n",
659                          current_round,
660                          stats_context->total_nse_cross);
661       GNUNET_DISK_file_write (data_file, buf, buf_len);
662       buf_len =
663         GNUNET_snprintf (buf, sizeof (buf),
664                          "TOTAL_NSE_EXTRA_%u: %u \n",
665                          current_round,
666                          stats_context->total_nse_extra);
667       GNUNET_DISK_file_write (data_file, buf, buf_len);
668       buf_len =
669         GNUNET_snprintf (buf, sizeof (buf),
670                          "TOTAL_NSE_DISCARDED_%u: %u \n",
671                          current_round,
672                          stats_context->total_discarded);
673       GNUNET_DISK_file_write (data_file, buf, buf_len);    
674     }  
675   GNUNET_SCHEDULER_add_now (&next_round, NULL);
676   GNUNET_free (stats_context);
677 }
678
679
680 /**
681  * Callback function to process statistic values.
682  *
683  * @param cls struct StatsContext
684  * @param peer the peer the statistics belong to
685  * @param subsystem name of subsystem that created the statistic
686  * @param name the name of the datum
687  * @param value the current value
688  * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
689  * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
690  */
691 static int
692 statistics_iterator (void *cls, 
693                      const struct GNUNET_TESTBED_Peer *peer,
694                      const char *subsystem, const char *name, uint64_t value,
695                      int is_persistent)
696 {
697   struct StatsContext *stats_context = cls;
698   char buf[512];
699   size_t buf_len;
700
701   if (0 != strcmp (subsystem, "nse"))
702     return GNUNET_OK;
703   if (0 == strcmp (name, "# flood messages received"))
704     {
705       stats_context->total_nse_received_messages += value;
706       if ( (verbose > 1) && 
707            (NULL != data_file) )
708         {
709           buf_len =
710             GNUNET_snprintf (buf, sizeof (buf),
711                              "%p %u RECEIVED\n", 
712                              peer, value);
713           GNUNET_DISK_file_write (data_file, buf, buf_len);
714         }
715     }
716   if (0 == strcmp (name, "# flood messages transmitted"))
717     {
718       stats_context->total_nse_transmitted_messages += value;
719       if ( (verbose > 1) &&
720            (NULL != data_file) )
721         {
722           buf_len =
723             GNUNET_snprintf (buf, sizeof (buf),
724                              "%p %u TRANSMITTED\n", 
725                              peer, value);
726           GNUNET_DISK_file_write (data_file, buf, buf_len);
727         }
728     }
729   if (0 == strcmp (name, "# cross messages"))
730     stats_context->total_nse_cross += value;    
731   if (0 == strcmp (name, "# extra messages"))    
732     stats_context->total_nse_extra += value;
733   if (0 == strcmp (name, "# flood messages discarded (clock skew too large)"))
734     stats_context->total_discarded += value;    
735   return GNUNET_OK;
736 }
737
738
739 /**
740  * Function called upon completion of the node start/stop operations
741  * for the current round.  Writes the new topology to disk.
742  */
743 static void
744 write_topology ()
745 {
746   char temp_output_file[1024];
747
748   if (NULL != topology_file)
749     {
750       GNUNET_snprintf (temp_output_file, sizeof (temp_output_file),
751                        "%s_%llu.dot", 
752                        topology_file, current_round);
753       GNUNET_TESTBED_overlay_write_topology_to_file (controller,
754                                                      temp_output_file);
755     }
756 }
757
758
759 /**
760  * We're at the end of a round.  Stop monitoring, write total
761  * number of connections to log and get full stats.  Then trigger
762  * the next round.
763  *
764  * @param cls unused, NULL
765  * @param tc unused
766  */
767 static void
768 finish_round (void *cls, 
769               const struct GNUNET_SCHEDULER_TaskContext *tc)
770 {
771   struct StatsContext *stats_context;
772   char buf[1024];
773   size_t buf_len;
774
775   GNUNET_log (GNUNET_ERROR_TYPE_INFO, 
776               "Have %u connections\n",
777               total_connections);
778   if (NULL != data_file)
779     {
780       buf_len = GNUNET_snprintf (buf, sizeof (buf),
781                                  "CONNECTIONS_0: %u\n", 
782                                  total_connections);
783       GNUNET_DISK_file_write (data_file, buf, buf_len);
784     }
785   close_monitor_connections ();    
786   stats_context = GNUNET_malloc (sizeof (struct StatsContext));
787   GNUNET_TESTBED_get_statistics (num_peers_in_round[current_round], 
788                                  daemons,                                
789                                  &statistics_iterator,
790                                  &stats_finished_callback,
791                                  stats_context);
792 }
793
794
795 /**
796  * We have reached the desired number of peers for the current round.
797  * Run it (by connecting and monitoring a few peers and waiting the
798  * specified delay before finishing the round).
799  */
800 static void
801 run_round ()
802 {
803   write_topology ();
804   connect_nse_service ();
805   GNUNET_SCHEDULER_add_delayed (wait_time,
806                                 &finish_round,
807                                 NULL);
808 }
809
810
811 /**
812  * Task run at the end of a round.  Disconnect from all monitored
813  * peers; then get statistics from *all* peers.
814  *
815  * @param cls NULL, unused
816  * @param tc unused
817  */
818 static void
819 next_round (void *cls, 
820             const struct GNUNET_SCHEDULER_TaskContext *tc)
821 {
822   unsigned int i;
823
824   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "disconnecting nse service of peers\n");
825   current_round++;
826   
827   if (current_round == num_rounds)
828     {
829       /* this was the last round, terminate */
830       GNUNET_SCHEDULER_shutdown ();
831       return;
832     }
833   if (num_peers_in_round[current_round] == peers_running)
834     {
835       /* no need to churn, just run next round */
836       run_round ();
837       return;
838     }
839
840   /* start peers if we have too few */
841   for (i=peers_running;i<num_peers_in_round[current_round];i++)
842     GNUNET_TESTBED_peer_start (daemons[i], NULL, NULL);
843
844   /* stop peers if we have too many */
845   for (i=num_peers_in_round[current_round];i<peers_running;i++)
846     GNUNET_TESTBED_peer_stop (daemons[i], NULL, NULL);
847 }
848
849
850 /**
851  * Function that will be called whenever something in the
852  * testbed changes.
853  *
854  * @param cls closure, NULL
855  * @param event information on what is happening
856  */
857 static void
858 master_controller_cb (void *cls, 
859                       const struct GNUNET_TESTBED_EventInformation *event)
860 {
861   switch (event->type)
862     {
863     case GNUNET_TESTBED_ET_PEER_START:
864       peers_running++;
865       if (num_peers_in_round[current_round] == peers_running)
866         run_round ();
867       break;
868     case GNUNET_TESTBED_ET_PEER_STOP:
869       peers_running--;
870       if (num_peers_in_round[current_round] == peers_running)
871         run_round ();
872       break;
873     case GNUNET_TESTBED_ET_CONNECT:
874       total_connections++;
875     case GNUNET_TESTBED_ET_DISCONNECT:
876       total_connections--;
877     default:
878       break;
879     }
880 }
881
882
883 static void
884 controller_start_cb (void *cls,
885                      const struct GNUNET_CONFIGURATION_Handle *cfg,
886                      int status)
887 {
888   if (GNUNET_OK != status)
889     {
890       copro = NULL;
891       GNUNET_SCHEDULER_shutdown ();
892       return;
893     }
894   num_hosts = GNUNET_TESTBED_hosts_load_from_file (hosts_file,
895                                                    &hosts);
896   if (0 == num_hosts)
897     {
898       fprintf (stderr,
899                "Failed to read host information from `%s'\n", 
900                hosts_file);
901       return;
902     }
903   controller = GNUNET_TESTBED_controller_connect (cfg,
904                                                NULL, 
905                                                0 /* mask */,
906                                                &master_controller_cb, NULL);
907
908   testbed = GNUNET_TESTBED_create (controller,
909                                    num_hosts, hosts, 
910                                    num_peers,
911                                    cfg,
912                                    0 /* FIXME: topology */,
913                                    NULL /* FIXME: topology options */);
914 }
915
916
917 /**
918  * Actual main function that runs the emulation.
919  *
920  * @param cls unused
921  * @param args remaining args, unused
922  * @param cfgfile name of the configuration
923  * @param cfg configuration handle
924  */
925 static void
926 run (void *cls, char *const *args, const char *cfgfile,
927      const struct GNUNET_CONFIGURATION_Handle *cfg)
928 {
929   char *tok;
930   unsigned int num;
931
932   ok = 1;
933   testing_cfg = GNUNET_CONFIGURATION_dup (cfg);
934   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Starting daemons.\n");
935   if (verbose)
936     GNUNET_CONFIGURATION_set_value_string (testing_cfg, "testing",
937                                            "use_progressbars", "YES");
938   if (NULL == num_peer_spec)
939   {
940     fprintf (stderr, "You need to specify the number of peers to run\n");
941     return;
942   }
943   for (tok = strtok (num_peer_spec, ","); NULL != tok; tok = strtok (NULL, ","))
944     {
945       if (1 != sscanf (tok, "%u", &num))
946         {
947           fprintf (stderr, "You need to specify numbers, not `%s'\n", tok);
948           return;
949         }
950       if (0 == num)
951         {
952           fprintf (stderr, "Refusing to run a round with 0 peers\n");
953           return;
954         }
955       GNUNET_array_grow (num_peers_in_round, num_rounds, num);
956       num_peers = GNUNET_MAX (num_peers, num);
957     }
958   if (0 == num_peers)
959     {
960       fprintf (stderr, "Refusing to run a testbed with no rounds\n");
961       return;
962     }
963   daemons = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_Peer*) * num_peers); 
964   if ( (NULL != data_filename) &&
965        (NULL == (data_file = 
966                  GNUNET_DISK_file_open (data_filename,
967                                         GNUNET_DISK_OPEN_READWRITE |
968                                         GNUNET_DISK_OPEN_TRUNCATE |
969                                         GNUNET_DISK_OPEN_CREATE,
970                                         GNUNET_DISK_PERM_USER_READ |
971                                         GNUNET_DISK_PERM_USER_WRITE))) )
972     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
973                               "open",
974                               data_filename);
975
976   if ( (NULL != output_filename) &&
977        (NULL == (output_file =
978                  GNUNET_DISK_file_open (output_filename,
979                                         GNUNET_DISK_OPEN_READWRITE |
980                                         GNUNET_DISK_OPEN_CREATE,
981                                         GNUNET_DISK_PERM_USER_READ |
982                                         GNUNET_DISK_PERM_USER_WRITE))) )
983     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open",
984                               output_filename);
985
986   if (NULL ==
987       (copro = GNUNET_TESTBED_controller_start (controller_ip, NULL,
988                                                 cfg,
989                                                 &controller_start_cb, NULL)))
990     {
991       fprintf (stderr,
992                "Failed to start controller\n");
993       return;
994     }
995   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
996                                 &shutdown_task, NULL);
997 }
998
999
1000 /**
1001  * Main function.
1002  *
1003  * @return 0 on success
1004  */
1005 int
1006 main (int argc, char *const *argv)
1007 {
1008   static struct GNUNET_GETOPT_CommandLineOption options[] = {
1009     {'C', "connections", "COUNT",
1010      gettext_noop ("limit to the number of connections to NSE services, 0 for none"),
1011      1, &GNUNET_GETOPT_set_string, &num_peer_spec},
1012     {'d', "details", "FILENAME",
1013      gettext_noop ("name of the file for writing connection information and statistics"),
1014      1, &GNUNET_GETOPT_set_string, &data_filename},
1015     {'H', "hosts", "FILENAME",
1016      gettext_noop ("name of the file with the login information for the testbed"),
1017      1, &GNUNET_GETOPT_set_string, &hosts_file},
1018     {'i', "ip", "CONTROLLER_IP",
1019      gettext_noop ("IP address of this system as seen by the rest of the testbed"),
1020      1, &GNUNET_GETOPT_set_string, &controller_ip},
1021     {'I', "interval", "DELAY",
1022      gettext_noop ("delay between queries to statistics during a round"),
1023      1, &GNUNET_GETOPT_set_relative_time, &interval},
1024     {'t', "topology", "FILENAME",
1025      gettext_noop ("prefix of the filenames we use for writing the topology for each round"),
1026      1, &GNUNET_GETOPT_set_string, &topology_file},
1027     {'o', "output", "FILENAME",
1028      gettext_noop ("name of the file for writing the main results"),
1029      1, &GNUNET_GETOPT_set_string, &output_filename},
1030     {'p', "peers", "NETWORKSIZESPEC",
1031      gettext_noop ("Number of peers to run in each round, separated by commas"),
1032      1, &GNUNET_GETOPT_set_string, &num_peer_spec},
1033     {'V', "verbose", NULL,
1034      gettext_noop ("be verbose (print progress information)"),
1035      0, &GNUNET_GETOPT_increment_value, &verbose},
1036     {'w', "wait", "DELAY",
1037      gettext_noop ("delay between rounds"),
1038      1, &GNUNET_GETOPT_set_relative_time, &wait_time},
1039     GNUNET_GETOPT_OPTION_END
1040   };
1041   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
1042     return 2;
1043   GNUNET_log_setup ("nse-profiler", "WARNING", NULL);
1044   if (GNUNET_OK !=
1045       GNUNET_PROGRAM_run (argc, argv, "nse-profiler",
1046                           gettext_noop
1047                           ("Measure quality and performance of the NSE service."),
1048                           options, &run, NULL))
1049     ok = 1;
1050   return ok;
1051 }
1052
1053 /* end of nse-profiler.c */