-fix fix
[oweals/gnunet.git] / src / mesh / gnunet-regex-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 /**
22  * @file mesh/gnunet-regex-profiler.c
23  * @brief Regex profiler for testing distributed regex use.
24  * @author Bart Polot
25  * @author Max Szengel
26  *
27  */
28
29 #include <string.h>
30
31 #include "platform.h"
32 #include "gnunet_applications.h"
33 #include "gnunet_util_lib.h"
34 #include "gnunet_mesh_service.h"
35 #include "gnunet_stream_lib.h"
36 #include "gnunet_testbed_service.h"
37
38 /**
39  * DLL of operations
40  */
41 struct DLLOperation
42 {
43   /**
44    * The testbed operation handle
45    */
46   struct GNUNET_TESTBED_Operation *op;
47
48   /**
49    * Closure
50    */
51   void *cls;
52
53   /**
54    * The next pointer for DLL
55    */
56   struct DLLOperation *next;
57
58   /**
59    * The prev pointer for DLL
60    */
61   struct DLLOperation *prev;
62 };
63
64
65 /**
66  * Available states during profiling
67  */
68 enum State
69 {
70   /**
71    * Initial state
72    */
73   STATE_INIT = 0,
74
75   /**
76    * Starting slaves
77    */
78   STATE_SLAVES_STARTING,
79
80   /**
81    * Creating peers
82    */
83   STATE_PEERS_CREATING,
84
85   /**
86    * Starting peers
87    */
88   STATE_PEERS_STARTING,
89
90   /**
91    * Linking peers
92    */
93   STATE_PEERS_LINKING,
94
95   /**
96    * Matching strings against announced regexes
97    */
98   STATE_SEARCH_REGEX,
99
100   /**
101    * Destroying peers; we can do this as the controller takes care of stopping a
102    * peer if it is running
103    */
104   STATE_PEERS_DESTROYING
105 };
106
107
108 /**
109  * Peer handles.
110  */
111 struct RegexPeer
112 {
113   /**
114    * Peer id.
115    */
116   unsigned int id;
117
118   /**
119    * Peer configuration handle.
120    */
121   struct GNUNET_CONFIGURATION_Handle *cfg;
122
123   /**
124    * The actual testbed peer handle.
125    */
126   struct GNUNET_TESTBED_Peer *peer_handle;
127
128   /**
129    * Host on which the peer is running.
130    */
131   struct GNUNET_TESTBED_Host *host_handle;
132
133   /**
134    * Filename of the peer's policy file.
135    */
136   char *policy_file;
137
138   /**
139    * Peers search string.
140    */
141   const char *search_str;
142
143   /**
144    * Set to GNUNET_YES if the peer successfully matched the above
145    * search string. GNUNET_NO if the string could not be matched
146    * during the profiler run. GNUNET_SYSERR if the string matching
147    * timed out. Undefined if search_str is NULL
148    */
149   int search_str_matched;
150
151   /**
152    * Peer's mesh handle.
153    */
154   struct GNUNET_MESH_Handle *mesh_handle;
155
156   /**
157    * Peer's mesh tunnel handle.
158    */
159   struct GNUNET_MESH_Tunnel *mesh_tunnel_handle;
160
161   /**
162    * Testbed operation handle for the mesh service.
163    */
164   struct GNUNET_TESTBED_Operation *mesh_op_handle;
165
166   /**
167    * Peers's statistics handle.
168    */
169   struct GNUNET_STATISTICS_Handle *stats_handle;
170
171   /**
172    * Testbed operation handle for the statistics service.
173    */
174   struct GNUNET_TESTBED_Operation *stats_op_handle;
175
176   /**
177    * The starting time of a profiling step.
178    */
179   struct GNUNET_TIME_Absolute prof_start_time;
180 };
181
182
183 /**
184  * An array of hosts loaded from the hostkeys file
185  */
186 static struct GNUNET_TESTBED_Host **hosts;
187
188 /**
189  * Array of peer handles used to pass to
190  * GNUNET_TESTBED_overlay_configure_topology
191  */
192 static struct GNUNET_TESTBED_Peer **peer_handles;
193
194 /**
195  * The array of peers; we fill this as the peers are given to us by the testbed
196  */
197 static struct RegexPeer *peers;
198
199 /**
200  * Host registration handle
201  */
202 static struct GNUNET_TESTBED_HostRegistrationHandle *reg_handle;
203
204 /**
205  * Handle to the master controller process
206  */
207 static struct GNUNET_TESTBED_ControllerProc *mc_proc;
208
209 /**
210  * Handle to the master controller
211  */
212 static struct GNUNET_TESTBED_Controller *mc;
213
214 /**
215  * Handle to global configuration
216  */
217 static struct GNUNET_CONFIGURATION_Handle *cfg;
218
219 /**
220  * Head of the operations list
221  */
222 static struct DLLOperation *dll_op_head;
223
224 /**
225  * Tail of the operations list
226  */
227 static struct DLLOperation *dll_op_tail;
228
229 /**
230  * Peer linking - topology operation
231  */
232 static struct GNUNET_TESTBED_Operation *topology_op;
233
234 /**
235  * Abort task identifier
236  */
237 static GNUNET_SCHEDULER_TaskIdentifier abort_task;
238
239 /**
240  * Host registration task identifier
241  */
242 static GNUNET_SCHEDULER_TaskIdentifier register_hosts_task;
243
244 /**
245  * Global event mask for all testbed events
246  */
247 static uint64_t event_mask;
248
249 /**
250  * The starting time of a profiling step
251  */
252 static struct GNUNET_TIME_Absolute prof_start_time;
253
254 /**
255  * Duration profiling step has taken
256  */
257 static struct GNUNET_TIME_Relative prof_time;
258
259 /**
260  * Number of peers to be started by the profiler
261  */
262 static unsigned int num_peers;
263
264 /**
265  * Number of hosts in the hosts array
266  */
267 static unsigned int num_hosts;
268
269 /**
270  * Factor of number of links. num_links = num_peers * linking_factor.
271  */
272 static unsigned int linking_factor;
273
274 /**
275  * Number of random links to be established between peers
276  */
277 static unsigned int num_links;
278
279 /**
280  * Number of times we try overlay connect operations
281  */
282 static unsigned int retry_links;
283
284 /**
285  * Continuous failures during overlay connect operations
286  */
287 static unsigned int cont_fails;
288
289 /**
290  * Global testing status
291  */
292 static int result;
293
294 /**
295  * current state of profiling
296  */
297 enum State state;
298
299 /**
300  * Folder where policy files are stored.
301  */
302 static char * policy_dir;
303
304 /**
305  * Search strings.
306  */
307 static char **search_strings;
308
309 /**
310  * Number of search strings.
311  */
312 static int num_search_strings;
313
314 /**
315  * Number of peers found with search strings.
316  */
317 static unsigned int peers_found;
318
319 /**
320  * Search task identifier
321  */
322 static GNUNET_SCHEDULER_TaskIdentifier search_task;
323
324 /**
325  * Search timeout task identifier.
326  */
327 static GNUNET_SCHEDULER_TaskIdentifier search_timeout_task;
328
329 /**
330  * Search timeout in seconds.
331  */
332 static struct GNUNET_TIME_Relative search_timeout = { 60000 };
333
334 /**
335  * How long do we wait before starting the search?
336  * Default: 1 m.
337  */
338 static struct GNUNET_TIME_Relative search_delay = { 60000 };
339
340 /**
341  * Delay to wait before starting to configure the overlay topology
342  */
343 static struct GNUNET_TIME_Relative conf_topo_delay = { 10000 };
344
345 /**
346  * File to log statistics to.
347  */
348 static struct GNUNET_DISK_FileHandle *data_file;
349
350 /**
351  * Filename to log statistics to.
352  */
353 static char *data_filename;
354
355 /**
356  * Maximal path compression length.
357  */
358 static unsigned int max_path_compression;
359
360 /******************************************************************************/
361 /******************************  DECLARATIONS  ********************************/
362 /******************************************************************************/
363
364
365 /**
366  * Method called whenever a peer has connected to the tunnel.
367  *
368  * @param cls closure
369  * @param peer_id peer identity the tunnel was created to, NULL on timeout
370  * @param atsi performance data for the connection
371  *
372  */
373 static void
374 mesh_peer_connect_handler (void *cls,
375                            const struct GNUNET_PeerIdentity* peer_id,
376                            const struct GNUNET_ATS_Information * atsi);
377
378
379 /**
380  * Method called whenever a peer has disconnected from the tunnel.
381  * Implementations of this callback must NOT call
382  * GNUNET_MESH_tunnel_destroy immediately, but instead schedule those
383  * to run in some other task later.  However, calling
384  * "GNUNET_MESH_notify_transmit_ready_cancel" is allowed.
385  *
386  * @param cls closure
387  * @param peer_id peer identity the tunnel stopped working with
388  */
389 static void
390 mesh_peer_disconnect_handler (void *cls,
391                               const struct GNUNET_PeerIdentity * peer_id);
392
393 /**
394  * Mesh connect callback.
395  *
396  * @param cls internal peer id.
397  * @param op operation handle.
398  * @param ca_result connect adapter result.
399  * @param emsg error message.
400  */
401 static void
402 mesh_connect_cb (void *cls, struct GNUNET_TESTBED_Operation *op,
403                  void *ca_result, const char *emsg);
404
405 /**
406  * Mesh connect adapter.
407  *
408  * @param cls not used.
409  * @param cfg configuration handle.
410  *
411  * @return
412  */
413 static void *
414 mesh_ca (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg);
415
416
417 /**
418  * Adapter function called to destroy a connection to
419  * the mesh service
420  *
421  * @param cls closure
422  * @param op_result service handle returned from the connect adapter
423  */
424 static void
425 mesh_da (void *cls, void *op_result);
426
427
428 /******************************************************************************/
429 /********************************  SHUTDOWN  **********************************/
430 /******************************************************************************/
431
432
433 /**
434  * Shutdown nicely
435  *
436  * @param cls NULL
437  * @param tc the task context
438  */
439 static void
440 do_shutdown (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
441 {
442   struct DLLOperation *dll_op;
443   struct RegexPeer *peer;
444   unsigned int nhost;
445   unsigned int peer_cnt;
446   unsigned int search_str_cnt;
447   char output_buffer[512];
448   size_t size;
449
450   if (GNUNET_SCHEDULER_NO_TASK != abort_task)
451     GNUNET_SCHEDULER_cancel (abort_task);
452   if (GNUNET_SCHEDULER_NO_TASK != register_hosts_task)
453     GNUNET_SCHEDULER_cancel (register_hosts_task);
454
455   for (peer_cnt = 0; peer_cnt < num_peers; peer_cnt++)
456   {
457     peer = &peers[peer_cnt];
458
459     if (GNUNET_YES != peer->search_str_matched && NULL != data_file)
460     {
461       prof_time = GNUNET_TIME_absolute_get_duration (peer->prof_start_time);
462       size =
463         GNUNET_snprintf (output_buffer,
464                          sizeof (output_buffer),
465                          "Search string not found: %s (%d)\nOn peer: %u (%p)\nWith policy file: %s\nAfter: %s\n",
466                          peer->search_str,
467                          peer->search_str_matched,
468                          peer->id,
469                          peer,
470                          peer->policy_file,
471                          GNUNET_STRINGS_relative_time_to_string (prof_time, GNUNET_NO));
472       if (size != GNUNET_DISK_file_write (data_file, output_buffer, size))
473         GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Unable to write to file!\n");
474     }
475
476     if (NULL != peers[peer_cnt].mesh_op_handle)
477       GNUNET_TESTBED_operation_done (peers[peer_cnt].mesh_op_handle);
478     if (NULL != peers[peer_cnt].stats_op_handle)
479       GNUNET_TESTBED_operation_done (peers[peer_cnt].stats_op_handle);
480   }
481
482   if (NULL != data_file)
483     GNUNET_DISK_file_close (data_file);
484
485   for (search_str_cnt = 0;
486        search_str_cnt < num_search_strings && NULL != search_strings;
487        search_str_cnt++)
488   {
489     GNUNET_free_non_null (search_strings[search_str_cnt]);
490   }
491   GNUNET_free_non_null (search_strings);
492
493   if (NULL != reg_handle)
494     GNUNET_TESTBED_cancel_registration (reg_handle);
495   if (NULL != topology_op)
496     GNUNET_TESTBED_operation_done (topology_op);
497   for (nhost = 0; nhost < num_hosts; nhost++)
498     if (NULL != hosts[nhost])
499       GNUNET_TESTBED_host_destroy (hosts[nhost]);
500   GNUNET_free_non_null (hosts);
501
502   while (NULL != (dll_op = dll_op_head))
503   {
504     GNUNET_TESTBED_operation_done (dll_op->op);
505     GNUNET_CONTAINER_DLL_remove (dll_op_head, dll_op_tail, dll_op);
506     GNUNET_free (dll_op);
507   }
508   if (NULL != mc)
509     GNUNET_TESTBED_controller_disconnect (mc);
510   if (NULL != mc_proc)
511     GNUNET_TESTBED_controller_stop (mc_proc);
512   if (NULL != cfg)
513     GNUNET_CONFIGURATION_destroy (cfg);
514
515   GNUNET_SCHEDULER_shutdown (); /* Stop scheduler to shutdown testbed run */
516 }
517
518
519 /**
520  * abort task to run on test timed out
521  *
522  * @param cls NULL
523  * @param tc the task context
524  */
525 static void
526 do_abort (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
527 {
528   GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Aborting\n");
529   abort_task = GNUNET_SCHEDULER_NO_TASK;
530   result = GNUNET_SYSERR;
531   GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
532 }
533
534
535 /******************************************************************************/
536 /*********************  STATISTICS SERVICE CONNECTIONS  ***********************/
537 /******************************************************************************/
538
539 /**
540  * Adapter function called to establish a connection to
541  * statistics service.
542  *
543  * @param cls closure
544  * @param cfg configuration of the peer to connect to; will be available until
545  *          GNUNET_TESTBED_operation_done() is called on the operation returned
546  *          from GNUNET_TESTBED_service_connect()
547  * @return service handle to return in 'op_result', NULL on error
548  */
549 static void *
550 stats_ca (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg)
551 {
552   return GNUNET_STATISTICS_create ("<driver>", cfg);
553 }
554
555
556 /**
557  * Adapter function called to destroy a connection to
558  * statistics service.
559  *
560  * @param cls closure
561  * @param op_result service handle returned from the connect adapter
562  */
563 static void
564 stats_da (void *cls, void *op_result)
565 {
566   struct RegexPeer *peer = cls;
567
568   GNUNET_assert (op_result == peer->stats_handle);
569
570   GNUNET_STATISTICS_destroy (peer->stats_handle, GNUNET_NO);
571   peer->stats_handle = NULL;
572 }
573
574
575 /**
576  * Process statistic values. Write all values to global 'data_file', if present.
577  *
578  * @param cls closure
579  * @param subsystem name of subsystem that created the statistic
580  * @param name the name of the datum
581  * @param value the current value
582  * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
583  * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
584  */
585 static int
586 stats_iterator (void *cls, const char *subsystem, const char *name,
587                 uint64_t value, int is_persistent)
588 {
589   struct RegexPeer *peer = cls;
590   char output_buffer[512];
591   size_t size;
592
593   if (NULL == data_file)
594   {
595     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
596                 "%p -> %s [%s]: %llu\n",
597                 peer, subsystem, name, value);
598     return GNUNET_OK;
599   }
600   size =
601     GNUNET_snprintf (output_buffer,
602                      sizeof (output_buffer),
603                      "%p [%s] %llu %s\n",
604                      peer,
605                      subsystem, value, name);
606   if (size != GNUNET_DISK_file_write (data_file, output_buffer, size))
607     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Unable to write to file!\n");
608
609   return GNUNET_OK;
610 }
611
612
613 /**
614  * Stats callback. Finish the stats testbed operation and when all stats have
615  * been iterated, shutdown the profiler.
616  *
617  * @param cls closure
618  * @param success GNUNET_OK if statistics were
619  *        successfully obtained, GNUNET_SYSERR if not.
620  */
621 static void
622 stats_cb (void *cls,
623           int success)
624 {
625   static unsigned int peer_cnt;
626   struct RegexPeer *peer = cls;
627
628   if (GNUNET_OK != success)
629   {
630     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
631                 "Getting statistics for peer %u failed!\n",
632                 peer->id);
633     return;
634   }
635
636   GNUNET_TESTBED_operation_done (peer->stats_op_handle);
637   peer->stats_op_handle = NULL;
638
639   if (++peer_cnt == num_search_strings)
640   {
641     struct GNUNET_TIME_Relative delay = { 100 };
642     GNUNET_SCHEDULER_add_delayed (delay, &do_shutdown, NULL);
643   }
644 }
645
646
647 /**
648  * Function called by testbed once we are connected to stats service. Create a
649  * mesh tunnel and try to match the peer's string.
650  *
651  * @param cls the 'struct RegexPeer' for which we connected to stats
652  * @param op connect operation handle
653  * @param ca_result handle to stats service
654  * @param emsg error message on failure
655  */
656 static void
657 stats_connect_cb (void *cls,
658                   struct GNUNET_TESTBED_Operation *op,
659                   void *ca_result,
660                   const char *emsg)
661 {
662   struct RegexPeer *peer = cls;
663
664   if (NULL == ca_result || NULL != emsg)
665   {
666     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
667                 "Failed to connect to statistics service on peer %u: %s\n",
668                 peer->id, emsg);
669
670     peer->stats_handle = NULL;
671     return;
672   }
673
674   GNUNET_assert (NULL != peer->mesh_handle);
675
676   peer->stats_handle = ca_result;
677
678   peer->mesh_tunnel_handle = GNUNET_MESH_tunnel_create (peer->mesh_handle,
679                                                         NULL,
680                                                         &mesh_peer_connect_handler,
681                                                         &mesh_peer_disconnect_handler,
682                                                         peer);
683
684   peer->prof_start_time = GNUNET_TIME_absolute_get ();
685
686   peer->search_str_matched = GNUNET_NO;
687   GNUNET_MESH_peer_request_connect_by_string (peer->mesh_tunnel_handle,
688                                               peer->search_str);
689 }
690
691
692 /******************************************************************************/
693 /************************  MESH SERVICE CONNECTIONS  **************************/
694 /******************************************************************************/
695
696 /**
697  * Method called whenever a peer has disconnected from the tunnel.
698  * Implementations of this callback must NOT call
699  * GNUNET_MESH_tunnel_destroy immediately, but instead schedule those
700  * to run in some other task later.  However, calling
701  * "GNUNET_MESH_notify_transmit_ready_cancel" is allowed.
702  *
703  * @param cls closure
704  * @param peer_id peer identity the tunnel stopped working with
705  */
706 static void
707 mesh_peer_disconnect_handler (void *cls,
708                               const struct GNUNET_PeerIdentity * peer_id)
709 {
710   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh peer disconnect handler.\n");
711 }
712
713
714 /**
715  * Method called when the mesh connection succeeded (or timed out), which means
716  * we've found a peer that announced a regex that matches our search string. Now
717  * get the statistics.
718  *
719  * @param cls closure
720  * @param peer_id peer identity the tunnel was created to, NULL on timeout
721  * @param atsi performance data for the connection
722  *
723  */
724 static void
725 mesh_peer_connect_handler (void *cls,
726                            const struct GNUNET_PeerIdentity* peer_id,
727                            const struct GNUNET_ATS_Information * atsi)
728 {
729   struct RegexPeer *peer = cls;
730   char output_buffer[512];
731   size_t size;
732
733   peers_found++;
734
735   if (NULL == peer_id)
736   {
737     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
738                 "String matching timed out for string %s on peer %u (%i/%i)\n",
739                 peer->search_str, peer->id, peers_found, num_search_strings);
740
741     printf ("String matching timed out for string %s on peer %u (%i/%i)\n",
742             peer->search_str, peer->id, peers_found, num_search_strings);
743
744     peer->search_str_matched = GNUNET_SYSERR;
745   }
746   else
747   {
748     prof_time = GNUNET_TIME_absolute_get_duration (peer->prof_start_time);
749     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
750                 "String %s successfully matched on peer %u after %s (%i/%i)\n",
751                 peer->search_str, peer->id, GNUNET_STRINGS_relative_time_to_string (prof_time, GNUNET_NO),
752                 peers_found, num_search_strings);
753
754     printf ("String %s successfully matched on peer %u after %s (%i/%i)\n",
755             peer->search_str, peer->id, GNUNET_STRINGS_relative_time_to_string (prof_time, GNUNET_NO),
756             peers_found, num_search_strings);
757     fflush (stdout);
758
759     peer->search_str_matched = GNUNET_YES;
760
761     if (NULL != data_file)
762     {
763       size =
764         GNUNET_snprintf (output_buffer,
765                          sizeof (output_buffer),
766                          "Peer: %u (%p)\nHost: %s\nPolicy file: %s\nSearch string: %s\nSearch duration: %s\n\n",
767                          peer->id,
768                          peer,
769                          GNUNET_TESTBED_host_get_hostname (peer->host_handle),
770                          peer->policy_file,
771                          peer->search_str,
772                          GNUNET_STRINGS_relative_time_to_string (prof_time, GNUNET_NO));
773
774       if (size != GNUNET_DISK_file_write (data_file, output_buffer, size))
775         GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Unable to write to file!\n");
776     }
777
778     if (NULL == peer->stats_handle)
779     {
780       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
781                   "Cannot get statistics for peer %u, stats handle is NULL!\n");
782       return;
783     }
784
785     if (NULL == GNUNET_STATISTICS_get (peer->stats_handle, "mesh", NULL,
786                                        GNUNET_TIME_UNIT_FOREVER_REL,
787                                        NULL,
788                                        &stats_iterator, peer))
789     {
790       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
791                   "Could not get mesh statistics of peer %u!\n", peer->id);
792     }
793     if (NULL == GNUNET_STATISTICS_get (peer->stats_handle, "regexprofiler", NULL,
794                                        GNUNET_TIME_UNIT_FOREVER_REL,
795                                        NULL,
796                                        &stats_iterator, peer))
797     {
798       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
799                   "Could not get regexprofiler statistics of peer %u!\n", peer->id);
800     }
801     if (NULL == GNUNET_STATISTICS_get (peer->stats_handle, "transport", NULL,
802                                        GNUNET_TIME_UNIT_FOREVER_REL,
803                                        NULL,
804                                        &stats_iterator, peer))
805     {
806       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
807                   "Could not get transport statistics of peer %u!\n", peer->id);
808     }
809     if (NULL == GNUNET_STATISTICS_get (peer->stats_handle, "dht", NULL,
810                                        GNUNET_TIME_UNIT_FOREVER_REL,
811                                        &stats_cb,
812                                        &stats_iterator, peer))
813     {
814       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
815                   "Could not get dht statistics of peer %u!\n", peer->id);
816     }
817   }
818
819   if (peers_found == num_search_strings)
820   {
821     prof_time = GNUNET_TIME_absolute_get_duration (prof_start_time);
822     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
823                 "All strings successfully matched in %s\n",
824                 GNUNET_STRINGS_relative_time_to_string (prof_time, GNUNET_NO));
825     printf ("All strings successfully matched. Shutting down.\n");
826     fflush (stdout);
827
828     if (GNUNET_SCHEDULER_NO_TASK != search_timeout_task)
829       GNUNET_SCHEDULER_cancel (search_timeout_task);
830   }
831 }
832
833
834 /**
835  * Connect by string timeout task. This will cancel the profiler after the
836  * specified timeout 'search_timeout'.
837  *
838  * @param cls NULL
839  * @param tc the task context
840  */
841 static void
842 do_connect_by_string_timeout (void *cls,
843                               const struct GNUNET_SCHEDULER_TaskContext * tc)
844 {
845   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
846               "Finding matches to all strings did not succeed after %s.\n",
847               GNUNET_STRINGS_relative_time_to_string (search_timeout, GNUNET_NO));
848   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
849               "Found %i of %i strings\n", peers_found, num_search_strings);
850
851   GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
852 }
853
854
855 /**
856  * Connect by string task that is run to search for a string in the NFA. It
857  * first connects to the mesh service, then connects to the stats service of
858  * this peer and then it starts the string search.
859  *
860  * @param cls NULL
861  * @param tc the task context
862  */
863 static void
864 do_connect_by_string (void *cls,
865                       const struct GNUNET_SCHEDULER_TaskContext * tc)
866 {
867   unsigned int search_cnt;
868   struct RegexPeer *peer;
869
870   printf ("Starting string search.\n");
871   fflush (stdout);
872
873   for (search_cnt = 0; search_cnt < num_search_strings; search_cnt++)
874   {
875     peer = &peers[search_cnt % num_peers];
876     peer->search_str = search_strings[search_cnt];
877     peer->search_str_matched = GNUNET_NO;
878
879     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
880                 "Searching for string \"%s\" on peer %d with file %s\n",
881                 peer->search_str, (search_cnt % num_peers), peer->policy_file);
882
883     /* First connect to mesh service, then connect to stats service
884        and then try connecting by string in stats_connect_cb */
885     peer->mesh_op_handle =
886       GNUNET_TESTBED_service_connect (NULL,
887                                       peers->peer_handle,
888                                       "mesh",
889                                       &mesh_connect_cb,
890                                       peer,
891                                       &mesh_ca,
892                                       &mesh_da,
893                                       peer);
894   }
895
896   search_timeout_task = GNUNET_SCHEDULER_add_delayed (search_timeout,
897                                                       &do_connect_by_string_timeout, NULL);
898 }
899
900
901 /**
902  * Mesh connect callback. Called when we are connected to the mesh service for
903  * the peer in 'cls'. If successfull we connect to the stats service of this
904  * peer and then try to match the search string of this peer.
905  *
906  * @param cls internal peer id.
907  * @param op operation handle.
908  * @param ca_result connect adapter result.
909  * @param emsg error message.
910  */
911 static void
912 mesh_connect_cb (void *cls, struct GNUNET_TESTBED_Operation *op,
913                  void *ca_result, const char *emsg)
914 {
915   struct RegexPeer *peer = (struct RegexPeer *) cls;
916
917   if (NULL != emsg || NULL == op || NULL == ca_result)
918   {
919     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Mesh connect failed: %s\n", emsg);
920     GNUNET_assert (0);
921   }
922
923   GNUNET_assert (peer->mesh_handle != NULL);
924   GNUNET_assert (peer->mesh_op_handle == op);
925   GNUNET_assert (peer->mesh_handle == ca_result);
926
927   /* First connect to the stats service, then start to search */
928   peer->stats_op_handle =
929     GNUNET_TESTBED_service_connect (NULL,
930                                     peers->peer_handle,
931                                     "statistics",
932                                     &stats_connect_cb,
933                                     peer,
934                                     &stats_ca,
935                                     &stats_da,
936                                     peer);
937 }
938
939
940 /**
941  * Mesh connect adapter. Opens a connection to the mesh service.
942  *
943  * @param cls not used.
944  * @param cfg configuration handle.
945  *
946  * @return
947  */
948 static void *
949 mesh_ca (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg)
950 {
951   GNUNET_MESH_ApplicationType app;
952   struct RegexPeer *peer = cls;
953
954   static struct GNUNET_MESH_MessageHandler handlers[] = {
955     {NULL, 0, 0}
956   };
957
958   app = (GNUNET_MESH_ApplicationType)0;
959
960   peer->mesh_handle =
961     GNUNET_MESH_connect (cfg, peer, NULL, NULL, handlers, &app);
962
963   return peer->mesh_handle;
964 }
965
966
967 /**
968  * Adapter function called to destroy a connection to
969  * the mesh service
970  *
971  * @param cls closure
972  * @param op_result service handle returned from the connect adapter
973  */
974 static void
975 mesh_da (void *cls, void *op_result)
976 {
977   struct RegexPeer *peer = (struct RegexPeer *) cls;
978
979   GNUNET_assert (peer->mesh_handle == op_result);
980
981   if (NULL != peer->mesh_tunnel_handle)
982   {
983     GNUNET_MESH_tunnel_destroy (peer->mesh_tunnel_handle);
984     peer->mesh_tunnel_handle = NULL;
985   }
986
987   if (NULL != peer->mesh_handle)
988   {
989     GNUNET_MESH_disconnect (peer->mesh_handle);
990     peer->mesh_handle = NULL;
991   }
992 }
993
994
995 /******************************************************************************/
996 /***************************  TESTBED PEER SETUP  *****************************/
997 /******************************************************************************/
998
999
1000 /**
1001  * Configure the peer overlay topology.
1002  *
1003  * @param cls NULL
1004  * @param tc the task context
1005  */
1006 static void
1007 do_configure_topology (void *cls,
1008                        const struct GNUNET_SCHEDULER_TaskContext * tc)
1009 {
1010   /*
1011     if (0 == linking_factor)
1012     linking_factor = 1;
1013     num_links = linking_factor * num_peers;
1014   */
1015   /* num_links = num_peers - 1; */
1016   num_links = linking_factor;
1017
1018   /* Do overlay connect */
1019   prof_start_time = GNUNET_TIME_absolute_get ();
1020   topology_op =
1021     GNUNET_TESTBED_overlay_configure_topology (NULL, num_peers, peer_handles,
1022                                                GNUNET_TESTBED_TOPOLOGY_ERDOS_RENYI,
1023                                                num_links,
1024                                                GNUNET_TESTBED_TOPOLOGY_DISABLE_AUTO_RETRY,
1025                                                GNUNET_TESTBED_TOPOLOGY_OPTION_END);
1026   if (NULL == topology_op)
1027   {
1028     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1029                 "Cannot create topology, op handle was NULL\n");
1030     GNUNET_assert (0);
1031   }
1032 }
1033
1034
1035 /**
1036  * Functions of this signature are called when a peer has been successfully
1037  * started or stopped.
1038  *
1039  * @param cls the closure from GNUNET_TESTBED_peer_start/stop()
1040  * @param emsg NULL on success; otherwise an error description
1041  */
1042 static void
1043 peer_churn_cb (void *cls, const char *emsg)
1044 {
1045   struct DLLOperation *dll_op = cls;
1046   struct GNUNET_TESTBED_Operation *op;
1047   static unsigned int started_peers;
1048   unsigned int peer_cnt;
1049
1050   op = dll_op->op;
1051   GNUNET_CONTAINER_DLL_remove (dll_op_head, dll_op_tail, dll_op);
1052   GNUNET_free (dll_op);
1053   if (NULL != emsg)
1054   {
1055     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1056          _("An operation has failed while starting peers\n"));
1057     GNUNET_TESTBED_operation_done (op);
1058     if (GNUNET_SCHEDULER_NO_TASK != abort_task)
1059       GNUNET_SCHEDULER_cancel (abort_task);
1060     abort_task = GNUNET_SCHEDULER_add_now (&do_abort, NULL);
1061     return;
1062   }
1063   GNUNET_TESTBED_operation_done (op);
1064   if (++started_peers == num_peers)
1065   {
1066     prof_time = GNUNET_TIME_absolute_get_duration (prof_start_time);
1067     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1068                 "All peers started successfully in %s\n",
1069                 GNUNET_STRINGS_relative_time_to_string (prof_time, GNUNET_NO));
1070     result = GNUNET_OK;
1071
1072     peer_handles = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_Peer *) * num_peers);
1073     for (peer_cnt = 0; peer_cnt < num_peers; peer_cnt++)
1074       peer_handles[peer_cnt] = peers[peer_cnt].peer_handle;
1075
1076     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1077                 "Waiting %s before starting to link peers\n",
1078                 GNUNET_STRINGS_relative_time_to_string (conf_topo_delay, GNUNET_YES));
1079
1080     printf ("Waiting %s before starting to link peers\n",
1081             GNUNET_STRINGS_relative_time_to_string (conf_topo_delay, GNUNET_YES));
1082     fflush (stdout);
1083
1084     state = STATE_PEERS_LINKING;
1085     GNUNET_SCHEDULER_add_delayed (conf_topo_delay, &do_configure_topology, NULL);
1086   }
1087 }
1088
1089
1090 /**
1091  * Functions of this signature are called when a peer has been successfully
1092  * created
1093  *
1094  * @param cls the closure from GNUNET_TESTBED_peer_create()
1095  * @param peer the handle for the created peer; NULL on any error during
1096  *          creation
1097  * @param emsg NULL if peer is not NULL; else MAY contain the error description
1098  */
1099 static void
1100 peer_create_cb (void *cls, struct GNUNET_TESTBED_Peer *peer, const char *emsg)
1101 {
1102   struct DLLOperation *dll_op = cls;
1103   struct RegexPeer *peer_ptr;
1104   static unsigned int created_peers;
1105   unsigned int peer_cnt;
1106
1107   if (NULL != emsg)
1108   {
1109     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1110          _("Creating a peer failed. Error: %s\n"), emsg);
1111     GNUNET_TESTBED_operation_done (dll_op->op);
1112     GNUNET_CONTAINER_DLL_remove (dll_op_head, dll_op_tail, dll_op);
1113     GNUNET_free (dll_op);
1114     if (GNUNET_SCHEDULER_NO_TASK != abort_task)
1115       GNUNET_SCHEDULER_cancel (abort_task);
1116     abort_task = GNUNET_SCHEDULER_add_now (&do_abort, NULL);
1117     return;
1118   }
1119
1120   peer_ptr = dll_op->cls;
1121   GNUNET_assert (NULL == peer_ptr->peer_handle);
1122   GNUNET_CONFIGURATION_destroy (peer_ptr->cfg);
1123   peer_ptr->cfg = NULL;
1124   peer_ptr->peer_handle = peer;
1125   GNUNET_TESTBED_operation_done (dll_op->op);
1126   GNUNET_CONTAINER_DLL_remove (dll_op_head, dll_op_tail, dll_op);
1127   GNUNET_free (dll_op);
1128
1129   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Peer %i created on host %s\n",
1130               peer_ptr->id,
1131               GNUNET_TESTBED_host_get_hostname (peer_ptr->host_handle));
1132
1133   if (++created_peers == num_peers)
1134   {
1135     prof_time = GNUNET_TIME_absolute_get_duration (prof_start_time);
1136     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1137                 "All peers created successfully in %s\n",
1138                 GNUNET_STRINGS_relative_time_to_string (prof_time, GNUNET_NO));
1139     /* Now peers are to be started */
1140     state = STATE_PEERS_STARTING;
1141     prof_start_time = GNUNET_TIME_absolute_get ();
1142     for (peer_cnt = 0; peer_cnt < num_peers; peer_cnt++)
1143     {
1144       dll_op = GNUNET_malloc (sizeof (struct DLLOperation));
1145       dll_op->op = GNUNET_TESTBED_peer_start (dll_op, peers[peer_cnt].peer_handle,
1146                                               &peer_churn_cb, dll_op);
1147       GNUNET_CONTAINER_DLL_insert_tail (dll_op_head, dll_op_tail, dll_op);
1148     }
1149   }
1150 }
1151
1152
1153 /**
1154  * Function called with a filename for each file in the policy directory. Create
1155  * a peer for each filename and update the peer's configuration to include the
1156  * max_path_compression specified as a command line argument as well as the
1157  * policy_file for this peer. The gnunet-service-regexprofiler service is
1158  * automatically started on this peer. The service reads the configurration and
1159  * announces the regexes stored in the policy file 'filename'.
1160  *
1161  * @param cls closure
1162  * @param filename complete filename (absolute path)
1163  * @return GNUNET_OK to continue to iterate,
1164  *  GNUNET_SYSERR to abort iteration with error!
1165  */
1166 static int
1167 policy_filename_cb (void *cls, const char *filename)
1168 {
1169   static unsigned int peer_cnt;
1170   struct DLLOperation *dll_op;
1171   struct RegexPeer *peer = &peers[peer_cnt];
1172
1173   GNUNET_assert (NULL != peer);
1174
1175   peer->policy_file = GNUNET_strdup (filename);
1176
1177   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Creating peer %i on host %s for policy file %s\n",
1178               peer->id,
1179               GNUNET_TESTBED_host_get_hostname (peer->host_handle),
1180               filename);
1181
1182   /* Set configuration options specific for this peer
1183      (max_path_compression and policy_file */
1184   peer->cfg = GNUNET_CONFIGURATION_dup (cfg);
1185   GNUNET_CONFIGURATION_set_value_number (peer->cfg, "REGEXPROFILER",
1186                                          "MAX_PATH_COMPRESSION",
1187                                          (unsigned long long)max_path_compression);
1188   GNUNET_CONFIGURATION_set_value_string (peer->cfg, "REGEXPROFILER",
1189                                          "POLICY_FILE", filename);
1190
1191   dll_op = GNUNET_malloc (sizeof (struct DLLOperation));
1192   dll_op->cls = &peers[peer_cnt];
1193   dll_op->op = GNUNET_TESTBED_peer_create (mc,
1194                                            peer->host_handle,
1195                                            peer->cfg,
1196                                            &peer_create_cb,
1197                                            dll_op);
1198   GNUNET_CONTAINER_DLL_insert_tail (dll_op_head, dll_op_tail, dll_op);
1199
1200   peer_cnt++;
1201
1202   return GNUNET_OK;
1203 }
1204
1205
1206 /**
1207  * Controller event callback.
1208  *
1209  * @param cls NULL
1210  * @param event the controller event
1211  */
1212 static void
1213 controller_event_cb (void *cls,
1214                      const struct GNUNET_TESTBED_EventInformation *event)
1215 {
1216   struct DLLOperation *dll_op;
1217   struct GNUNET_TESTBED_Operation *op;
1218   int ret;
1219
1220   switch (state)
1221   {
1222   case STATE_SLAVES_STARTING:
1223     switch (event->type)
1224     {
1225     case GNUNET_TESTBED_ET_OPERATION_FINISHED:
1226       {
1227         static unsigned int slaves_started;
1228         unsigned int peer_cnt;
1229
1230         dll_op = event->details.operation_finished.op_cls;
1231         GNUNET_CONTAINER_DLL_remove (dll_op_head, dll_op_tail, dll_op);
1232         GNUNET_free (dll_op);
1233         op = event->details.operation_finished.operation;
1234         if (NULL != event->details.operation_finished.emsg)
1235         {
1236           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1237                _("An operation has failed while starting slaves\n"));
1238           GNUNET_TESTBED_operation_done (op);
1239           if (GNUNET_SCHEDULER_NO_TASK != abort_task)
1240             GNUNET_SCHEDULER_cancel (abort_task);
1241           abort_task = GNUNET_SCHEDULER_add_now (&do_abort, NULL);
1242           return;
1243         }
1244         GNUNET_TESTBED_operation_done (op);
1245         /* Proceed to start peers */
1246         if (++slaves_started == num_hosts - 1)
1247         {
1248           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1249                       "All slaves started successfully\n");
1250
1251           state = STATE_PEERS_CREATING;
1252           prof_start_time = GNUNET_TIME_absolute_get ();
1253
1254           if (-1 == (ret = GNUNET_DISK_directory_scan (policy_dir,
1255                                                        NULL,
1256                                                        NULL)))
1257           {
1258             GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1259                         _("No files found in `%s'\n"),
1260                         policy_dir);
1261             GNUNET_SCHEDULER_shutdown ();
1262             return;
1263           }
1264           num_peers = (unsigned int) ret;
1265           peers = GNUNET_malloc (sizeof (struct RegexPeer) * num_peers);
1266
1267           /* Initialize peers */
1268           for (peer_cnt = 0; peer_cnt < num_peers; peer_cnt++)
1269           {
1270             struct RegexPeer *peer = &peers[peer_cnt];
1271             peer->id = peer_cnt;
1272             peer->policy_file = NULL;
1273             /* Do not start peers on hosts[0] (master controller) */
1274             peer->host_handle = hosts[1 + (peer_cnt % (num_hosts -1))];
1275             peer->mesh_handle = NULL;
1276             peer->mesh_tunnel_handle = NULL;
1277             peer->stats_handle = NULL;
1278             peer->stats_op_handle = NULL;
1279             peer->search_str = NULL;
1280             peer->search_str_matched = GNUNET_NO;
1281           }
1282
1283           GNUNET_DISK_directory_scan (policy_dir,
1284                                       &policy_filename_cb,
1285                                       NULL);
1286         }
1287       }
1288       break;
1289     default:
1290       GNUNET_assert (0);
1291     }
1292     break;
1293   case STATE_PEERS_STARTING:
1294     switch (event->type)
1295     {
1296     case GNUNET_TESTBED_ET_OPERATION_FINISHED:
1297       /* Control reaches here when peer start fails */
1298     case GNUNET_TESTBED_ET_PEER_START:
1299       /* we handle peer starts in peer_churn_cb */
1300       break;
1301     default:
1302       GNUNET_assert (0);
1303     }
1304     break;
1305   case STATE_PEERS_LINKING:
1306    switch (event->type)
1307    {
1308      static unsigned int established_links;
1309    case GNUNET_TESTBED_ET_OPERATION_FINISHED:
1310      /* Control reaches here when a peer linking operation fails */
1311      if (NULL != event->details.operation_finished.emsg)
1312      {
1313        GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1314                    _("An operation has failed while linking\n"));
1315        printf ("F");
1316        fflush (stdout);
1317        retry_links++;
1318      }
1319      /* We do no retries, consider this link as established */
1320      /* break; */
1321    case GNUNET_TESTBED_ET_CONNECT:
1322    {
1323      char output_buffer[512];
1324      size_t size;
1325
1326      if (0 == established_links)
1327        printf ("Establishing links .");
1328      else
1329      {
1330        printf (".");
1331        fflush (stdout);
1332      }
1333      if (++established_links == num_links)
1334      {
1335        fflush (stdout);
1336        prof_time = GNUNET_TIME_absolute_get_duration (prof_start_time);
1337        GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1338                    "%u links established in %s\n",
1339                    num_links,
1340                    GNUNET_STRINGS_relative_time_to_string (prof_time, GNUNET_NO));
1341        result = GNUNET_OK;
1342        GNUNET_free (peer_handles);
1343
1344        if (NULL != data_file)
1345        {
1346          size =
1347            GNUNET_snprintf (output_buffer,
1348                             sizeof (output_buffer),
1349                             "# of peers: %u\n# of links established: %u\n"
1350                             "Time to establish links: %s\nLinking failures: %u\n"
1351                             "path compression length: %u\n# of search strings: %u\n",
1352                             num_peers,
1353                             (established_links - cont_fails),
1354                             GNUNET_STRINGS_relative_time_to_string (prof_time, GNUNET_NO),
1355                             cont_fails,
1356                             max_path_compression,
1357                             num_search_strings);
1358
1359          if (size != GNUNET_DISK_file_write (data_file, output_buffer, size))
1360            GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Unable to write to file!\n");
1361        }
1362
1363        printf ("\nWaiting %s before starting to search.\n",
1364                GNUNET_STRINGS_relative_time_to_string (search_delay, GNUNET_YES));
1365        fflush (stdout);
1366
1367        GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1368                    "Waiting %s before starting to search.\n",
1369                    GNUNET_STRINGS_relative_time_to_string (search_delay, GNUNET_NO));
1370
1371        state = STATE_SEARCH_REGEX;
1372
1373        search_task = GNUNET_SCHEDULER_add_delayed (search_delay,
1374                                                    &do_connect_by_string, NULL);
1375      }
1376    }
1377    break;
1378    default:
1379      GNUNET_assert (0);
1380    }
1381    break;
1382   case STATE_SEARCH_REGEX:
1383   {
1384     /* Handled in service connect callback */
1385     break;
1386   }
1387   default:
1388     switch (state)
1389     {
1390     case STATE_PEERS_CREATING:
1391       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Failed to create peer\n");
1392       break;
1393     default:
1394       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1395                   "Unexpected controller_cb with state %i!\n", state);
1396     }
1397     GNUNET_assert (0);
1398   }
1399 }
1400
1401
1402 /**
1403  * Task to register all hosts available in the global host list.
1404  *
1405  * @param cls NULL
1406  * @param tc the scheduler task context
1407  */
1408 static void
1409 register_hosts (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1410
1411
1412 /**
1413  * Callback which will be called to after a host registration succeeded or failed
1414  *
1415  * @param cls the closure
1416  * @param emsg the error message; NULL if host registration is successful
1417  */
1418 static void
1419 host_registration_completion (void *cls, const char *emsg)
1420 {
1421   reg_handle = NULL;
1422   if (NULL != emsg)
1423   {
1424     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1425                 _("Host registration failed for a host. Error: %s\n"), emsg);
1426     if (GNUNET_SCHEDULER_NO_TASK != abort_task)
1427       GNUNET_SCHEDULER_cancel (abort_task);
1428     abort_task = GNUNET_SCHEDULER_add_now (&do_abort, NULL);
1429     return;
1430   }
1431   register_hosts_task = GNUNET_SCHEDULER_add_now (&register_hosts, NULL);
1432 }
1433
1434
1435 /**
1436  * Task to register all hosts available in the global host list.
1437  *
1438  * @param cls NULL
1439  * @param tc the scheduler task context
1440  */
1441 static void
1442 register_hosts (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1443 {
1444   struct DLLOperation *dll_op;
1445   static unsigned int reg_host;
1446   unsigned int slave;
1447
1448   register_hosts_task = GNUNET_SCHEDULER_NO_TASK;
1449   if (reg_host == num_hosts - 1)
1450   {
1451     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1452                 "All hosts successfully registered\n");
1453     /* Start slaves */
1454     state = STATE_SLAVES_STARTING;
1455     for (slave = 1; slave < num_hosts; slave++)
1456     {
1457       dll_op = GNUNET_malloc (sizeof (struct DLLOperation));
1458       dll_op->op = GNUNET_TESTBED_controller_link (dll_op,
1459                                                    mc,
1460                                                    hosts[slave],
1461                                                    hosts[0],
1462                                                    cfg,
1463                                                    GNUNET_YES);
1464       GNUNET_CONTAINER_DLL_insert_tail (dll_op_head, dll_op_tail, dll_op);
1465     }
1466     return;
1467   }
1468   reg_handle = GNUNET_TESTBED_register_host (mc, hosts[++reg_host],
1469                                              host_registration_completion,
1470                                              NULL);
1471 }
1472
1473
1474 /**
1475  * Callback to signal successfull startup of the controller process.
1476  *
1477  * @param cls the closure from GNUNET_TESTBED_controller_start()
1478  * @param config the configuration with which the controller has been started;
1479  *          NULL if status is not GNUNET_OK
1480  * @param status GNUNET_OK if the startup is successfull; GNUNET_SYSERR if not,
1481  *          GNUNET_TESTBED_controller_stop() shouldn't be called in this case
1482  */
1483 static void
1484 status_cb (void *cls, const struct GNUNET_CONFIGURATION_Handle *config, int status)
1485 {
1486   if (GNUNET_SCHEDULER_NO_TASK != abort_task)
1487     GNUNET_SCHEDULER_cancel (abort_task);
1488   if (GNUNET_OK != status)
1489   {
1490     mc_proc = NULL;
1491     abort_task = GNUNET_SCHEDULER_add_now (&do_abort, NULL);
1492     return;
1493   }
1494   event_mask = 0;
1495   event_mask |= (1LL << GNUNET_TESTBED_ET_PEER_START);
1496   event_mask |= (1LL << GNUNET_TESTBED_ET_PEER_STOP);
1497   event_mask |= (1LL << GNUNET_TESTBED_ET_CONNECT);
1498   event_mask |= (1LL << GNUNET_TESTBED_ET_DISCONNECT);
1499   event_mask |= (1LL << GNUNET_TESTBED_ET_OPERATION_FINISHED);
1500   mc = GNUNET_TESTBED_controller_connect (config, hosts[0], event_mask,
1501                                           &controller_event_cb, NULL);
1502   if (NULL == mc)
1503   {
1504     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1505                 _("Unable to connect to master controller -- Check config\n"));
1506     abort_task = GNUNET_SCHEDULER_add_now (&do_abort, NULL);
1507     return;
1508   }
1509   register_hosts_task = GNUNET_SCHEDULER_add_now (&register_hosts, NULL);
1510   abort_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1511                                              &do_abort, NULL);
1512 }
1513
1514
1515 /**
1516  * Load search strings from given filename. One search string per line.
1517  *
1518  * @param filename filename of the file containing the search strings.
1519  * @param strings set of strings loaded from file. Caller needs to free this
1520  *                if number returned is greater than zero.
1521  * @param limit upper limit on the number of strings read from the file
1522  * @return number of strings found in the file. GNUNET_SYSERR on error.
1523  */
1524 static int
1525 load_search_strings (const char *filename, char ***strings, unsigned int limit)
1526 {
1527   char *data;
1528   char *buf;
1529   uint64_t filesize;
1530   unsigned int offset;
1531   int str_cnt;
1532   unsigned int i;
1533
1534   if (NULL == filename)
1535   {
1536     return GNUNET_SYSERR;
1537   }
1538
1539   if (GNUNET_YES != GNUNET_DISK_file_test (filename))
1540   {
1541     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1542                 "Could not find search strings file %s\n", filename);
1543     return GNUNET_SYSERR;
1544   }
1545   if (GNUNET_OK != GNUNET_DISK_file_size (filename, &filesize, GNUNET_YES, GNUNET_YES))
1546     filesize = 0;
1547   if (0 == filesize)
1548   {
1549     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Search strings file %s is empty.\n", filename);
1550     return GNUNET_SYSERR;
1551   }
1552   data = GNUNET_malloc (filesize);
1553   if (filesize != GNUNET_DISK_fn_read (filename, data, filesize))
1554   {
1555     GNUNET_free (data);
1556     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Could not read search strings file %s.\n",
1557          filename);
1558     return GNUNET_SYSERR;
1559   }
1560   buf = data;
1561   offset = 0;
1562   str_cnt = 0;
1563   while (offset < (filesize - 1) && str_cnt < limit)
1564   {
1565     offset++;
1566     if (((data[offset] == '\n')) && (buf != &data[offset]))
1567     {
1568       data[offset] = '\0';
1569       str_cnt++;
1570       buf = &data[offset + 1];
1571     }
1572     else if ((data[offset] == '\n') || (data[offset] == '\0'))
1573       buf = &data[offset + 1];
1574   }
1575   *strings = GNUNET_malloc (sizeof (char *) * str_cnt);
1576   offset = 0;
1577   for (i = 0; i < str_cnt; i++)
1578   {
1579     (*strings)[i] = GNUNET_strdup (&data[offset]);
1580     offset += strlen ((*strings)[i]) + 1;
1581   }
1582   free (data);
1583   return str_cnt;
1584 }
1585
1586
1587 /**
1588  * Main function that will be run by the scheduler.
1589  *
1590  * @param cls closure
1591  * @param args remaining command-line arguments
1592  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
1593  * @param config configuration
1594  */
1595 static void
1596 run (void *cls, char *const *args, const char *cfgfile,
1597      const struct GNUNET_CONFIGURATION_Handle *config)
1598 {
1599   unsigned int nhost;
1600   unsigned int nsearchstrs;
1601
1602   if (NULL == args[0])
1603   {
1604     fprintf (stderr, _("No hosts-file specified on command line. Exiting.\n"));
1605     return;
1606   }
1607   if (NULL == args[1])
1608   {
1609     fprintf (stderr, _("No policy directory specified on command line. Exiting.\n"));
1610     return;
1611   }
1612   num_hosts = GNUNET_TESTBED_hosts_load_from_file (args[0], &hosts);
1613   if (0 == num_hosts)
1614   {
1615     fprintf (stderr, _("No hosts loaded. Need at least one host\n"));
1616     return;
1617   }
1618   for (nhost = 0; nhost < num_hosts; nhost++)
1619   {
1620     if (GNUNET_YES != GNUNET_TESTBED_is_host_habitable (hosts[nhost], config))
1621     {
1622       fprintf (stderr, _("Host %s cannot start testbed\n"),
1623                          GNUNET_TESTBED_host_get_hostname (hosts[nhost]));
1624       break;
1625     }
1626   }
1627   if (num_hosts != nhost)
1628   {
1629     fprintf (stderr, _("Exiting\n"));
1630     GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1631     return;
1632   }
1633   if (NULL == config)
1634   {
1635     fprintf (stderr, _("No configuration file given. Exiting\n"));
1636     GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1637     return;
1638   }
1639   if ( (NULL != data_filename) &&
1640        (NULL == (data_file =
1641                  GNUNET_DISK_file_open (data_filename,
1642                                         GNUNET_DISK_OPEN_READWRITE |
1643                                         GNUNET_DISK_OPEN_TRUNCATE |
1644                                         GNUNET_DISK_OPEN_CREATE,
1645                                         GNUNET_DISK_PERM_USER_READ |
1646                                         GNUNET_DISK_PERM_USER_WRITE))) )
1647     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
1648                               "open",
1649                               data_filename);
1650   if (GNUNET_YES != GNUNET_DISK_directory_test (args[1]))
1651   {
1652     fprintf (stderr, _("Specified policies directory does not exist. Exiting.\n"));
1653     GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1654     return;
1655   }
1656   policy_dir = args[1];
1657   if (GNUNET_YES != GNUNET_DISK_file_test (args[2]))
1658   {
1659     fprintf (stderr, _("No search strings file given. Exiting.\n"));
1660     GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1661     return;
1662   }
1663   nsearchstrs = load_search_strings (args[2], &search_strings, num_search_strings);
1664   if (num_search_strings != nsearchstrs)
1665   {
1666     num_search_strings = nsearchstrs;
1667     fprintf (stderr, _("Error loading search strings. Given file does not contain enough strings. Exiting.\n"));
1668     GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1669     return;
1670   }
1671   if (0 >= num_search_strings || NULL == search_strings)
1672   {
1673     fprintf (stderr, _("Error loading search strings. Exiting.\n"));
1674     GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1675     return;
1676   }
1677   unsigned int i;
1678   for (i = 0; i < num_search_strings; i++)
1679     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "search string: %s\n", search_strings[i]);
1680   cfg = GNUNET_CONFIGURATION_dup (config);
1681   mc_proc =
1682       GNUNET_TESTBED_controller_start (GNUNET_TESTBED_host_get_hostname
1683                                        (hosts[0]),
1684                                        hosts[0],
1685                                        cfg,
1686                                        status_cb,
1687                                        NULL);
1688   abort_task =
1689       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
1690                                     (GNUNET_TIME_UNIT_SECONDS, 5), &do_abort,
1691                                     NULL);
1692 }
1693
1694
1695 /**
1696  * Main function.
1697  *
1698  * @param argc argument count
1699  * @param argv argument values
1700  * @return 0 on success
1701  */
1702 int
1703 main (int argc, char *const *argv)
1704 {
1705   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
1706     {'d', "details", "FILENAME",
1707      gettext_noop ("name of the file for writing statistics"),
1708      1, &GNUNET_GETOPT_set_string, &data_filename},
1709     {'n', "num-links", "COUNT",
1710       gettext_noop ("create COUNT number of random links between peers"),
1711       GNUNET_YES, &GNUNET_GETOPT_set_uint, &linking_factor },
1712     {'t', "matching-timeout", "TIMEOUT",
1713       gettext_noop ("wait TIMEOUT before considering a string match as failed"),
1714       GNUNET_YES, &GNUNET_GETOPT_set_relative_time, &search_timeout },
1715     {'s', "search-delay", "DELAY",
1716       gettext_noop ("wait DELAY before starting string search"),
1717       GNUNET_YES, &GNUNET_GETOPT_set_relative_time, &search_delay },
1718     {'a', "num-search-strings", "COUNT",
1719       gettext_noop ("number of search strings to read from search strings file"),
1720       GNUNET_YES, &GNUNET_GETOPT_set_uint, &num_search_strings },
1721     {'p', "max-path-compression", "MAX_PATH_COMPRESSION",
1722      gettext_noop ("maximum path compression length"),
1723      1, &GNUNET_GETOPT_set_uint, &max_path_compression},
1724     GNUNET_GETOPT_OPTION_END
1725   };
1726   int ret;
1727
1728   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
1729     return 2;
1730
1731   result = GNUNET_SYSERR;
1732   ret =
1733       GNUNET_PROGRAM_run (argc, argv, "gnunet-regex-profiler [OPTIONS] hosts-file policy-dir search-strings-file",
1734                           _("Profiler for regex/mesh"),
1735                           options, &run, NULL);
1736   GNUNET_free ((void*) argv);
1737   if (GNUNET_OK != ret)
1738     return ret;
1739   if (GNUNET_OK != result)
1740     return 1;
1741   return 0;
1742 }