- cosmetic changes
[oweals/gnunet.git] / src / regex / gnunet-regex-profiler.c
1 /*
2      This file is part of GNUnet.
3      (C) 2011 - 2013 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file mesh/gnunet-regex-profiler.c
23  * @brief Regex profiler for testing distributed regex use.
24  * @author Bartlomiej Polot
25  * @author Maximilian 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_regex_lib.h"
35 #include "gnunet_dht_service.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 dht handle.
153    */
154   struct GNUNET_DHT_Handle *dht_handle;
155
156   /**
157    * Handle to a running regex search.
158    */
159    struct GNUNET_REGEX_search_handle *search_handle;
160
161   /**
162    * Testbed operation handle for the dht service.
163    */
164   struct GNUNET_TESTBED_Operation *dht_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  * The handle for whether a host is habitable or not
236  */
237 struct GNUNET_TESTBED_HostHabitableCheckHandle **hc_handles;
238
239 /**
240  * Abort task identifier
241  */
242 static GNUNET_SCHEDULER_TaskIdentifier abort_task;
243
244 /**
245  * Shutdown task identifier
246  */
247 static GNUNET_SCHEDULER_TaskIdentifier shutdown_task;
248
249 /**
250  * Host registration task identifier
251  */
252 static GNUNET_SCHEDULER_TaskIdentifier register_hosts_task;
253
254 /**
255  * Global event mask for all testbed events
256  */
257 static uint64_t event_mask;
258
259 /**
260  * The starting time of a profiling step
261  */
262 static struct GNUNET_TIME_Absolute prof_start_time;
263
264 /**
265  * Duration profiling step has taken
266  */
267 static struct GNUNET_TIME_Relative prof_time;
268
269 /**
270  * Number of peers to be started by the profiler
271  */
272 static unsigned int num_peers;
273
274 /**
275  * Number of hosts in the hosts array
276  */
277 static unsigned int num_hosts;
278
279 /**
280  * Factor of number of links. num_links = num_peers * linking_factor.
281  */
282 static unsigned int linking_factor;
283
284 /**
285  * Number of random links to be established between peers
286  */
287 static unsigned int num_links;
288
289 /**
290  * Number of times we try overlay connect operations
291  */
292 static unsigned int retry_links;
293
294 /**
295  * Continuous failures during overlay connect operations
296  */
297 static unsigned int cont_fails;
298
299 /**
300  * Global testing status
301  */
302 static int result;
303
304 /**
305  * current state of profiling
306  */
307 enum State state;
308
309 /**
310  * Folder where policy files are stored.
311  */
312 static char * policy_dir;
313
314 /**
315  * Search strings.
316  */
317 static char **search_strings;
318
319 /**
320  * Number of search strings.
321  */
322 static int num_search_strings;
323
324 /**
325  * Number of peers found with search strings.
326  */
327 static unsigned int peers_found;
328
329 /**
330  * Search task identifier
331  */
332 static GNUNET_SCHEDULER_TaskIdentifier search_task;
333
334 /**
335  * Search timeout task identifier.
336  */
337 static GNUNET_SCHEDULER_TaskIdentifier search_timeout_task;
338
339 /**
340  * Search timeout in seconds.
341  */
342 static struct GNUNET_TIME_Relative search_timeout = { 60000 };
343
344 /**
345  * How long do we wait before starting the search?
346  * Default: 1 m.
347  */
348 static struct GNUNET_TIME_Relative search_delay = { 60000 };
349
350 /**
351  * File to log statistics to.
352  */
353 static struct GNUNET_DISK_FileHandle *data_file;
354
355 /**
356  * Filename to log statistics to.
357  */
358 static char *data_filename;
359
360 /**
361  * Maximal path compression length.
362  */
363 static unsigned int max_path_compression;
364
365 /**
366  * If we should distribute the search evenly throught all peers (each
367  * peer searches for a string) or if only one peer should search for
368  * all strings.
369  */
370 static int no_distributed_search;
371
372 /**
373  * Prefix used for regex announcing. We need to prefix the search
374  * strings with it, in order to find something.
375  */
376 static char * regex_prefix;
377
378
379 /******************************************************************************/
380 /******************************  DECLARATIONS  ********************************/
381 /******************************************************************************/
382
383
384 /**
385  * Search callback function.
386  *
387  * @param cls Closure provided in GNUNET_REGEX_search.
388  * @param id Peer providing a regex that matches the string.
389  * @param get_path Path of the get request.
390  * @param get_path_length Lenght of get_path.
391  * @param put_path Path of the put request.
392  * @param put_path_length Length of the put_path.
393  */
394 static void
395 regex_found_handler (void *cls,
396                      const struct GNUNET_PeerIdentity *id,
397                      const struct GNUNET_PeerIdentity *get_path,
398                      unsigned int get_path_length,
399                      const struct GNUNET_PeerIdentity *put_path,
400                      unsigned int put_path_length);
401
402
403 /**
404  * Mesh connect callback.
405  *
406  * @param cls internal peer id.
407  * @param op operation handle.
408  * @param ca_result connect adapter result.
409  * @param emsg error message.
410  */
411 static void
412 dht_connect_cb (void *cls, struct GNUNET_TESTBED_Operation *op,
413                  void *ca_result, const char *emsg);
414
415 /**
416  * DHT connect adapter.
417  *
418  * @param cls not used.
419  * @param cfg configuration handle.
420  *
421  * @return
422  */
423 static void *
424 dht_ca (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg);
425
426
427 /**
428  * Adapter function called to destroy a connection to
429  * the DHT service
430  *
431  * @param cls closure
432  * @param op_result service handle returned from the connect adapter
433  */
434 static void
435 dht_da (void *cls, void *op_result);
436
437
438 /**
439  * Function called by testbed once we are connected to stats
440  * service. Get the statistics for the services of interest.
441  *
442  * @param cls the 'struct RegexPeer' for which we connected to stats
443  * @param op connect operation handle
444  * @param ca_result handle to stats service
445  * @param emsg error message on failure
446  */
447 static void
448 stats_connect_cb (void *cls,
449                   struct GNUNET_TESTBED_Operation *op,
450                   void *ca_result,
451                   const char *emsg);
452
453
454 /**
455  * Task to collect all statistics from all peers, will shutdown the
456  * profiler, when done.
457  *
458  * @param cls NULL
459  * @param tc the task context
460  */
461 static void
462 do_collect_stats (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
463
464
465 /******************************************************************************/
466 /********************************  SHUTDOWN  **********************************/
467 /******************************************************************************/
468
469
470 /**
471  * Shutdown nicely
472  *
473  * @param cls NULL
474  * @param tc the task context
475  */
476 static void
477 do_shutdown (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
478 {
479   struct DLLOperation *dll_op;
480   struct RegexPeer *peer;
481   unsigned int nhost;
482   unsigned int peer_cnt;
483   unsigned int search_str_cnt;
484   char output_buffer[512];
485   size_t size;
486
487   shutdown_task = GNUNET_SCHEDULER_NO_TASK;
488   if (GNUNET_SCHEDULER_NO_TASK != abort_task)
489     GNUNET_SCHEDULER_cancel (abort_task);
490   if (NULL != hc_handles)
491   {
492     for (nhost = 0; nhost < num_hosts; nhost++)
493       if (NULL != hc_handles[nhost])
494         GNUNET_TESTBED_is_host_habitable_cancel (hc_handles[nhost]);
495     GNUNET_free (hc_handles);
496     hc_handles = NULL;
497   }
498   if (GNUNET_SCHEDULER_NO_TASK != register_hosts_task)
499     GNUNET_SCHEDULER_cancel (register_hosts_task);
500
501   for (peer_cnt = 0; peer_cnt < num_peers; peer_cnt++)
502   {
503     peer = &peers[peer_cnt];
504
505     if (GNUNET_YES != peer->search_str_matched && NULL != data_file)
506     {
507       prof_time = GNUNET_TIME_absolute_get_duration (peer->prof_start_time);
508       size =
509         GNUNET_snprintf (output_buffer,
510                          sizeof (output_buffer),
511                          "%p Search string not found: %s (%d)\n%p On peer: %u (%p)\n%p With policy file: %s\n%p After: %s\n",
512                          peer,
513                          peer->search_str,
514                          peer->search_str_matched,
515                          peer,
516                          peer->id,
517                          peer,
518                          peer,
519                          peer->policy_file,
520                          peer,
521                          GNUNET_STRINGS_relative_time_to_string (prof_time, GNUNET_NO));
522       if (size != GNUNET_DISK_file_write (data_file, output_buffer, size))
523         GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Unable to write to file!\n");
524     }
525
526     if (NULL != peers[peer_cnt].dht_op_handle)
527       GNUNET_TESTBED_operation_done (peers[peer_cnt].dht_op_handle);
528     if (NULL != peers[peer_cnt].stats_op_handle)
529       GNUNET_TESTBED_operation_done (peers[peer_cnt].stats_op_handle);
530   }
531
532   if (NULL != data_file)
533     GNUNET_DISK_file_close (data_file);
534
535   for (search_str_cnt = 0;
536        search_str_cnt < num_search_strings && NULL != search_strings;
537        search_str_cnt++)
538   {
539     GNUNET_free_non_null (search_strings[search_str_cnt]);
540   }
541   GNUNET_free_non_null (search_strings);
542
543   if (NULL != reg_handle)
544     GNUNET_TESTBED_cancel_registration (reg_handle);
545   if (NULL != topology_op)
546     GNUNET_TESTBED_operation_done (topology_op);
547   for (nhost = 0; nhost < num_hosts; nhost++)
548     if (NULL != hosts[nhost])
549       GNUNET_TESTBED_host_destroy (hosts[nhost]);
550   GNUNET_free_non_null (hosts);
551
552   while (NULL != (dll_op = dll_op_head))
553   {
554     GNUNET_TESTBED_operation_done (dll_op->op);
555     GNUNET_CONTAINER_DLL_remove (dll_op_head, dll_op_tail, dll_op);
556     GNUNET_free (dll_op);
557   }
558   if (NULL != mc)
559     GNUNET_TESTBED_controller_disconnect (mc);
560   if (NULL != mc_proc)
561     GNUNET_TESTBED_controller_stop (mc_proc);
562   if (NULL != cfg)
563     GNUNET_CONFIGURATION_destroy (cfg);
564
565   GNUNET_SCHEDULER_shutdown (); /* Stop scheduler to shutdown testbed run */
566 }
567
568
569 /**
570  * abort task to run on test timed out
571  *
572  * @param cls NULL
573  * @param tc the task context
574  */
575 static void
576 do_abort (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
577 {
578   unsigned long i = (unsigned long) cls;
579
580   GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Aborting %lu...\n", i);
581   abort_task = GNUNET_SCHEDULER_NO_TASK;
582   result = GNUNET_SYSERR;
583   if (GNUNET_SCHEDULER_NO_TASK != shutdown_task)
584     GNUNET_SCHEDULER_cancel (shutdown_task);
585   shutdown_task = GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
586 }
587
588
589 /******************************************************************************/
590 /*********************  STATISTICS SERVICE CONNECTIONS  ***********************/
591 /******************************************************************************/
592
593 /**
594  * Adapter function called to establish a connection to
595  * statistics service.
596  *
597  * @param cls closure
598  * @param cfg configuration of the peer to connect to; will be available until
599  *          GNUNET_TESTBED_operation_done() is called on the operation returned
600  *          from GNUNET_TESTBED_service_connect()
601  * @return service handle to return in 'op_result', NULL on error
602  */
603 static void *
604 stats_ca (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg)
605 {
606   return GNUNET_STATISTICS_create ("<driver>", cfg);
607 }
608
609
610 /**
611  * Adapter function called to destroy a connection to
612  * statistics service.
613  *
614  * @param cls closure
615  * @param op_result service handle returned from the connect adapter
616  */
617 static void
618 stats_da (void *cls, void *op_result)
619 {
620   struct RegexPeer *peer = cls;
621
622   GNUNET_assert (op_result == peer->stats_handle);
623
624   GNUNET_STATISTICS_destroy (peer->stats_handle, GNUNET_NO);
625   peer->stats_handle = NULL;
626 }
627
628
629 /**
630  * Process statistic values. Write all values to global 'data_file', if present.
631  *
632  * @param cls closure
633  * @param subsystem name of subsystem that created the statistic
634  * @param name the name of the datum
635  * @param value the current value
636  * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
637  * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
638  */
639 static int
640 stats_iterator (void *cls, const char *subsystem, const char *name,
641                 uint64_t value, int is_persistent)
642 {
643   struct RegexPeer *peer = cls;
644   char output_buffer[512];
645   size_t size;
646
647   if (NULL == data_file)
648   {
649     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
650                 "%p -> %s [%s]: %llu\n",
651                 peer, subsystem, name, value);
652     return GNUNET_OK;
653   }
654   size =
655     GNUNET_snprintf (output_buffer,
656                      sizeof (output_buffer),
657                      "%p [%s] %llu %s\n",
658                      peer,
659                      subsystem, value, name);
660   if (size != GNUNET_DISK_file_write (data_file, output_buffer, size))
661     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Unable to write to file!\n");
662
663   return GNUNET_OK;
664 }
665
666
667 /**
668  * Stats callback. Finish the stats testbed operation and when all stats have
669  * been iterated, shutdown the profiler.
670  *
671  * @param cls closure
672  * @param success GNUNET_OK if statistics were
673  *        successfully obtained, GNUNET_SYSERR if not.
674  */
675 static void
676 stats_cb (void *cls,
677           int success)
678 {
679   static unsigned int peer_cnt;
680   struct RegexPeer *peer = cls;
681
682   if (GNUNET_OK != success)
683   {
684     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
685                 "Getting statistics for peer %u failed!\n",
686                 peer->id);
687     return;
688   }
689
690   GNUNET_assert (NULL != peer->stats_op_handle);
691
692   GNUNET_TESTBED_operation_done (peer->stats_op_handle);
693   peer->stats_op_handle = NULL;
694
695   peer_cnt++;
696   peer = &peers[peer_cnt];
697
698   if (peer_cnt == num_peers)
699   {
700     struct GNUNET_TIME_Relative delay = { 100 };
701     shutdown_task = GNUNET_SCHEDULER_add_delayed (delay, &do_shutdown, NULL);
702   }
703   else
704   {
705     peer->stats_op_handle =
706       GNUNET_TESTBED_service_connect (NULL,
707                                       peer->peer_handle,
708                                       "statistics",
709                                       &stats_connect_cb,
710                                       peer,
711                                       &stats_ca,
712                                       &stats_da,
713                                       peer);
714   }
715 }
716
717
718 /**
719  * Function called by testbed once we are connected to stats
720  * service. Get the statistics for the services of interest.
721  *
722  * @param cls the 'struct RegexPeer' for which we connected to stats
723  * @param op connect operation handle
724  * @param ca_result handle to stats service
725  * @param emsg error message on failure
726  */
727 static void
728 stats_connect_cb (void *cls,
729                   struct GNUNET_TESTBED_Operation *op,
730                   void *ca_result,
731                   const char *emsg)
732 {
733   struct RegexPeer *peer = cls;
734
735   if (NULL == ca_result || NULL != emsg)
736   {
737     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
738                 "Failed to connect to statistics service on peer %u: %s\n",
739                 peer->id, emsg);
740
741     peer->stats_handle = NULL;
742     return;
743   }
744
745   peer->stats_handle = ca_result;
746
747   if (NULL == GNUNET_STATISTICS_get (peer->stats_handle, NULL, NULL,
748                                      GNUNET_TIME_UNIT_FOREVER_REL,
749                                      &stats_cb,
750                                      &stats_iterator, peer))
751   {
752     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
753                 "Could not get statistics of peer %u!\n", peer->id);
754   }
755 }
756
757
758 /**
759  * Task to collect all statistics from all peers, will shutdown the
760  * profiler, when done.
761  *
762  * @param cls NULL
763  * @param tc the task context
764  */
765 static void
766 do_collect_stats (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
767 {
768   struct RegexPeer *peer = &peers[0];
769
770   GNUNET_assert (NULL != peer->peer_handle);
771
772   peer->stats_op_handle =
773     GNUNET_TESTBED_service_connect (NULL,
774                                     peer->peer_handle,
775                                     "statistics",
776                                     &stats_connect_cb,
777                                     peer,
778                                     &stats_ca,
779                                     &stats_da,
780                                     peer);
781 }
782
783
784 /******************************************************************************/
785 /************************  MESH SERVICE CONNECTIONS  **************************/
786 /******************************************************************************/
787
788 /**
789  * Method called when we've found a peer that announced a regex
790  * that matches our search string. Now get the statistics.
791  *
792  * @param cls Closure provided in GNUNET_REGEX_search.
793  * @param id Peer providing a regex that matches the string.
794  * @param get_path Path of the get request.
795  * @param get_path_length Lenght of get_path.
796  * @param put_path Path of the put request.
797  * @param put_path_length Length of the put_path.
798  */
799 static void
800 regex_found_handler (void *cls,
801                      const struct GNUNET_PeerIdentity *id,
802                      const struct GNUNET_PeerIdentity *get_path,
803                      unsigned int get_path_length,
804                      const struct GNUNET_PeerIdentity *put_path,
805                      unsigned int put_path_length)
806 {
807   struct RegexPeer *peer = cls;
808   char output_buffer[512];
809   size_t size;
810
811   if (GNUNET_YES == peer->search_str_matched)
812   {
813     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
814                 "String %s on peer %u already matched!\n",
815                 peer->search_str, peer->id);
816     return;
817   }
818
819   peers_found++;
820
821   if (NULL == id)
822   {
823     // FIXME not possible right now
824     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
825                 "String matching timed out for string %s on peer %u (%i/%i)\n",
826                 peer->search_str, peer->id, peers_found, num_search_strings);
827
828     printf ("String matching timed out for string %s on peer %u (%i/%i)\n",
829             peer->search_str, peer->id, peers_found, num_search_strings);
830
831     peer->search_str_matched = GNUNET_SYSERR;
832   }
833   else
834   {
835     prof_time = GNUNET_TIME_absolute_get_duration (peer->prof_start_time);
836     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
837                 "String %s successfully matched on peer %u after %s (%i/%i)\n",
838                 peer->search_str, peer->id, GNUNET_STRINGS_relative_time_to_string (prof_time, GNUNET_NO),
839                 peers_found, num_search_strings);
840
841     printf ("String %s successfully matched on peer %u after %s (%i/%i)\n",
842             peer->search_str, peer->id, GNUNET_STRINGS_relative_time_to_string (prof_time, GNUNET_NO),
843             peers_found, num_search_strings);
844     fflush (stdout);
845
846     peer->search_str_matched = GNUNET_YES;
847
848     if (NULL != data_file)
849     {
850       size =
851         GNUNET_snprintf (output_buffer,
852                          sizeof (output_buffer),
853                          "%p Peer: %u\n%p Host: %s\n%p Policy file: %s\n"
854                          "%p Search string: %s\n%p Search duration: %s\n\n",
855                          peer, peer->id,
856                          peer,
857                          GNUNET_TESTBED_host_get_hostname (peer->host_handle),
858                          peer, peer->policy_file,
859                          peer, peer->search_str,
860                          peer,
861                          GNUNET_STRINGS_relative_time_to_string (prof_time,
862                                                                  GNUNET_NO));
863
864       if (size != GNUNET_DISK_file_write (data_file, output_buffer, size))
865         GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Unable to write to file!\n");
866     }
867   }
868
869   GNUNET_TESTBED_operation_done (peer->dht_op_handle);
870   peer->dht_op_handle = NULL;
871
872   if (peers_found == num_search_strings)
873   {
874     prof_time = GNUNET_TIME_absolute_get_duration (prof_start_time);
875     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
876                 "All strings successfully matched in %s\n",
877                 GNUNET_STRINGS_relative_time_to_string (prof_time, GNUNET_NO));
878     printf ("All strings successfully matched.\n");
879     fflush (stdout);
880
881     if (GNUNET_SCHEDULER_NO_TASK != search_timeout_task)
882       GNUNET_SCHEDULER_cancel (search_timeout_task);
883
884     printf ("Collecting stats and shutting down.\n");
885     GNUNET_SCHEDULER_add_now (&do_collect_stats, NULL);
886   }
887 }
888
889
890 /**
891  * Connect by string timeout task. This will cancel the profiler after the
892  * specified timeout 'search_timeout'.
893  *
894  * @param cls NULL
895  * @param tc the task context
896  */
897 static void
898 do_connect_by_string_timeout (void *cls,
899                               const struct GNUNET_SCHEDULER_TaskContext * tc)
900 {
901   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
902               "Finding matches to all strings did not succeed after %s.\n",
903               GNUNET_STRINGS_relative_time_to_string (search_timeout, GNUNET_NO));
904   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
905               "Found %i of %i strings\n", peers_found, num_search_strings);
906
907   printf ("Search timed out after %s. Collecting stats and shutting down.\n", 
908           GNUNET_STRINGS_relative_time_to_string (search_timeout, GNUNET_NO));
909   fflush (stdout);
910
911   GNUNET_SCHEDULER_add_now (&do_collect_stats, NULL);
912 }
913
914
915 /**
916  * Connect by string task that is run to search for a string in the
917  * NFA. It first connects to the mesh service and when a connection is
918  * established it starts to search for the string.
919  *
920  * @param cls NULL
921  * @param tc the task context
922  */
923 static void
924 do_connect_by_string (void *cls,
925                       const struct GNUNET_SCHEDULER_TaskContext * tc)
926 {
927   printf ("Starting string search.\n");
928   fflush (stdout);
929
930   peers[0].search_str = search_strings[0];
931   peers[0].search_str_matched = GNUNET_NO;
932
933   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
934               "Searching for string \"%s\" on peer %d with file %s\n",
935               peers[0].search_str, 0, peers[0].policy_file);
936
937     /* First connect to mesh service, then search for string. Next
938        connect will be in mesh_connect_cb */
939     peers[0].dht_op_handle =
940       GNUNET_TESTBED_service_connect (NULL,
941                                       peers[0].peer_handle,
942                                       "dht",
943                                       &dht_connect_cb,
944                                       &peers[0],
945                                       &dht_ca,
946                                       &dht_da,
947                                       &peers[0]);
948
949   search_timeout_task = GNUNET_SCHEDULER_add_delayed (search_timeout,
950                                                       &do_connect_by_string_timeout, NULL);
951 }
952
953
954 /**
955  * DHT connect callback. Called when we are connected to the dht service for
956  * the peer in 'cls'. If successfull we connect to the stats service of this
957  * peer and then try to match the search string of this peer.
958  *
959  * @param cls internal peer id.
960  * @param op operation handle.
961  * @param ca_result connect adapter result.
962  * @param emsg error message.
963  */
964 static void
965 dht_connect_cb (void *cls, struct GNUNET_TESTBED_Operation *op,
966                 void *ca_result, const char *emsg)
967 {
968   struct RegexPeer *peer = (struct RegexPeer *) cls;
969   static unsigned int peer_cnt;
970   unsigned int next_p;
971
972   if (NULL != emsg || NULL == op || NULL == ca_result)
973   {
974     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "DHT connect failed: %s\n", emsg);
975     GNUNET_abort ();
976   }
977
978   GNUNET_assert (NULL != peer->dht_handle);
979   GNUNET_assert (peer->dht_op_handle == op);
980   GNUNET_assert (peer->dht_handle == ca_result);
981
982   peer->search_str_matched = GNUNET_NO;
983   peer->search_handle = GNUNET_REGEX_search (peer->dht_handle,
984                                              peer->search_str,
985                                              &regex_found_handler, NULL,
986                                              NULL);
987   peer->prof_start_time = GNUNET_TIME_absolute_get ();
988
989   if (peer_cnt < (num_search_strings - 1))
990   {
991     if (GNUNET_YES == no_distributed_search)
992       next_p = 0;
993     else
994       next_p = (++peer_cnt % num_peers);
995
996     peers[next_p].search_str = search_strings[next_p];
997     peers[next_p].search_str_matched = GNUNET_NO;
998
999     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1000                 "Searching for string \"%s\" on peer %d with file %s\n",
1001                 peers[next_p].search_str, next_p, peers[next_p].policy_file);
1002
1003     /* FIXME
1004      * dont connect to a new dht for each peer, we might want to seach for n
1005      * strings on m peers where n > m
1006      */
1007     peers[next_p].dht_op_handle =
1008       GNUNET_TESTBED_service_connect (NULL,
1009                                       peers[next_p].peer_handle,
1010                                       "dht",
1011                                       &dht_connect_cb,
1012                                       &peers[next_p],
1013                                       &dht_ca,
1014                                       &dht_da,
1015                                       &peers[next_p]);
1016   }
1017 }
1018
1019
1020 /**
1021  * DHT connect adapter. Opens a connection to the dht service.
1022  *
1023  * @param cls Closure (peer).
1024  * @param cfg Configuration handle.
1025  *
1026  * @return
1027  */
1028 static void *
1029 dht_ca (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg)
1030 {
1031   struct RegexPeer *peer = cls;
1032
1033   peer->dht_handle = GNUNET_DHT_connect (cfg, 32);
1034
1035   return peer->dht_handle;
1036 }
1037
1038
1039 /**
1040  * Adapter function called to destroy a connection to the dht service.
1041  *
1042  * @param cls Closure (peer).
1043  * @param op_result Service handle returned from the connect adapter.
1044  */
1045 static void
1046 dht_da (void *cls, void *op_result)
1047 {
1048   struct RegexPeer *peer = (struct RegexPeer *) cls;
1049
1050   GNUNET_assert (peer->dht_handle == op_result);
1051
1052   if (NULL != peer->search_handle)
1053   {
1054     GNUNET_REGEX_search_cancel (peer->search_handle);
1055     peer->search_handle = NULL;
1056   }
1057
1058   if (NULL != peer->dht_handle)
1059   {
1060     GNUNET_DHT_disconnect (peer->dht_handle);
1061     peer->dht_handle = NULL;
1062   }
1063 }
1064
1065
1066 /******************************************************************************/
1067 /***************************  TESTBED PEER SETUP  *****************************/
1068 /******************************************************************************/
1069
1070
1071 /**
1072  * Configure the peer overlay topology.
1073  *
1074  * @param cls NULL
1075  * @param tc the task context
1076  */
1077 static void
1078 do_configure_topology (void *cls,
1079                        const struct GNUNET_SCHEDULER_TaskContext * tc)
1080 {
1081   /*
1082     if (0 == linking_factor)
1083     linking_factor = 1;
1084     num_links = linking_factor * num_peers;
1085   */
1086   /* num_links = num_peers - 1; */
1087   num_links = linking_factor;
1088
1089   /* Do overlay connect */
1090   prof_start_time = GNUNET_TIME_absolute_get ();
1091   topology_op =
1092     GNUNET_TESTBED_overlay_configure_topology (NULL, num_peers, peer_handles,
1093                                                NULL,
1094                                                GNUNET_TESTBED_TOPOLOGY_ERDOS_RENYI,
1095                                                num_links,
1096                                                GNUNET_TESTBED_TOPOLOGY_DISABLE_AUTO_RETRY,
1097                                                GNUNET_TESTBED_TOPOLOGY_OPTION_END);
1098   if (NULL == topology_op)
1099   {
1100     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1101                 "Cannot create topology, op handle was NULL\n");
1102     GNUNET_assert (0);
1103   }
1104 }
1105
1106
1107 /**
1108  * Functions of this signature are called when a peer has been successfully
1109  * started or stopped.
1110  *
1111  * @param cls the closure from GNUNET_TESTBED_peer_start/stop()
1112  * @param emsg NULL on success; otherwise an error description
1113  */
1114 static void
1115 peer_churn_cb (void *cls, const char *emsg)
1116 {
1117   struct DLLOperation *dll_op = cls;
1118   struct GNUNET_TESTBED_Operation *op;
1119   static unsigned int started_peers;
1120   unsigned int peer_cnt;
1121
1122   op = dll_op->op;
1123   GNUNET_CONTAINER_DLL_remove (dll_op_head, dll_op_tail, dll_op);
1124   GNUNET_free (dll_op);
1125   if (NULL != emsg)
1126   {
1127     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1128          _("An operation has failed while starting peers\n"));
1129     GNUNET_TESTBED_operation_done (op);
1130     if (GNUNET_SCHEDULER_NO_TASK != abort_task)
1131       GNUNET_SCHEDULER_cancel (abort_task);
1132     abort_task = GNUNET_SCHEDULER_add_now (&do_abort, (void*) __LINE__);
1133     return;
1134   }
1135   GNUNET_TESTBED_operation_done (op);
1136   if (++started_peers == num_peers)
1137   {
1138     prof_time = GNUNET_TIME_absolute_get_duration (prof_start_time);
1139     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1140                 "All peers started successfully in %s\n",
1141                 GNUNET_STRINGS_relative_time_to_string (prof_time, GNUNET_NO));
1142     result = GNUNET_OK;
1143
1144     peer_handles = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_Peer *) * num_peers);
1145     for (peer_cnt = 0; peer_cnt < num_peers; peer_cnt++)
1146       peer_handles[peer_cnt] = peers[peer_cnt].peer_handle;
1147
1148     state = STATE_PEERS_LINKING;
1149     GNUNET_SCHEDULER_add_now (&do_configure_topology, NULL);
1150   }
1151 }
1152
1153
1154 /**
1155  * Functions of this signature are called when a peer has been successfully
1156  * created
1157  *
1158  * @param cls the closure from GNUNET_TESTBED_peer_create()
1159  * @param peer the handle for the created peer; NULL on any error during
1160  *          creation
1161  * @param emsg NULL if peer is not NULL; else MAY contain the error description
1162  */
1163 static void
1164 peer_create_cb (void *cls, struct GNUNET_TESTBED_Peer *peer, const char *emsg)
1165 {
1166   struct DLLOperation *dll_op = cls;
1167   struct RegexPeer *peer_ptr;
1168   static unsigned int created_peers;
1169   unsigned int peer_cnt;
1170
1171   if (NULL != emsg)
1172   {
1173     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1174          _("Creating a peer failed. Error: %s\n"), emsg);
1175     GNUNET_TESTBED_operation_done (dll_op->op);
1176     GNUNET_CONTAINER_DLL_remove (dll_op_head, dll_op_tail, dll_op);
1177     GNUNET_free (dll_op);
1178     if (GNUNET_SCHEDULER_NO_TASK != abort_task)
1179       GNUNET_SCHEDULER_cancel (abort_task);
1180     abort_task = GNUNET_SCHEDULER_add_now (&do_abort, (void*) __LINE__);
1181     return;
1182   }
1183
1184   peer_ptr = dll_op->cls;
1185   GNUNET_assert (NULL == peer_ptr->peer_handle);
1186   GNUNET_CONFIGURATION_destroy (peer_ptr->cfg);
1187   peer_ptr->cfg = NULL;
1188   peer_ptr->peer_handle = peer;
1189   GNUNET_TESTBED_operation_done (dll_op->op);
1190   GNUNET_CONTAINER_DLL_remove (dll_op_head, dll_op_tail, dll_op);
1191   GNUNET_free (dll_op);
1192
1193   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Peer %i created on host %s\n",
1194               peer_ptr->id,
1195               GNUNET_TESTBED_host_get_hostname (peer_ptr->host_handle));
1196
1197   if (++created_peers == num_peers)
1198   {
1199     prof_time = GNUNET_TIME_absolute_get_duration (prof_start_time);
1200     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1201                 "All peers created successfully in %s\n",
1202                 GNUNET_STRINGS_relative_time_to_string (prof_time, GNUNET_NO));
1203     /* Now peers are to be started */
1204     state = STATE_PEERS_STARTING;
1205     prof_start_time = GNUNET_TIME_absolute_get ();
1206     for (peer_cnt = 0; peer_cnt < num_peers; peer_cnt++)
1207     {
1208       dll_op = GNUNET_malloc (sizeof (struct DLLOperation));
1209       dll_op->op = GNUNET_TESTBED_peer_start (dll_op, peers[peer_cnt].peer_handle,
1210                                               &peer_churn_cb, dll_op);
1211       GNUNET_CONTAINER_DLL_insert_tail (dll_op_head, dll_op_tail, dll_op);
1212     }
1213   }
1214 }
1215
1216
1217 /**
1218  * Function called with a filename for each file in the policy directory. Create
1219  * a peer for each filename and update the peer's configuration to include the
1220  * max_path_compression specified as a command line argument as well as the
1221  * policy_file for this peer. The gnunet-service-regexprofiler service is
1222  * automatically started on this peer. The service reads the configurration and
1223  * announces the regexes stored in the policy file 'filename'.
1224  *
1225  * @param cls closure
1226  * @param filename complete filename (absolute path)
1227  * @return GNUNET_OK to continue to iterate,
1228  *  GNUNET_SYSERR to abort iteration with error!
1229  */
1230 static int
1231 policy_filename_cb (void *cls, const char *filename)
1232 {
1233   static unsigned int peer_cnt;
1234   struct DLLOperation *dll_op;
1235   struct RegexPeer *peer = &peers[peer_cnt];
1236
1237   GNUNET_assert (NULL != peer);
1238
1239   peer->policy_file = GNUNET_strdup (filename);
1240
1241   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Creating peer %i on host %s for policy file %s\n",
1242               peer->id,
1243               GNUNET_TESTBED_host_get_hostname (peer->host_handle),
1244               filename);
1245
1246   /* Set configuration options specific for this peer
1247      (max_path_compression and policy_file */
1248   peer->cfg = GNUNET_CONFIGURATION_dup (cfg);
1249   GNUNET_CONFIGURATION_set_value_number (peer->cfg, "REGEXPROFILER",
1250                                          "MAX_PATH_COMPRESSION",
1251                                          (unsigned long long)max_path_compression);
1252   GNUNET_CONFIGURATION_set_value_string (peer->cfg, "REGEXPROFILER",
1253                                          "POLICY_FILE", filename);
1254
1255   dll_op = GNUNET_malloc (sizeof (struct DLLOperation));
1256   dll_op->cls = &peers[peer_cnt];
1257   dll_op->op = GNUNET_TESTBED_peer_create (mc,
1258                                            peer->host_handle,
1259                                            peer->cfg,
1260                                            &peer_create_cb,
1261                                            dll_op);
1262   GNUNET_CONTAINER_DLL_insert_tail (dll_op_head, dll_op_tail, dll_op);
1263
1264   peer_cnt++;
1265
1266   return GNUNET_OK;
1267 }
1268
1269
1270 /**
1271  * Controller event callback.
1272  *
1273  * @param cls NULL
1274  * @param event the controller event
1275  */
1276 static void
1277 controller_event_cb (void *cls,
1278                      const struct GNUNET_TESTBED_EventInformation *event)
1279 {
1280   struct DLLOperation *dll_op;
1281   struct GNUNET_TESTBED_Operation *op;
1282   int ret;
1283
1284   switch (state)
1285   {
1286   case STATE_SLAVES_STARTING:
1287     switch (event->type)
1288     {
1289     case GNUNET_TESTBED_ET_OPERATION_FINISHED:
1290       {
1291         static unsigned int slaves_started;
1292         unsigned int peer_cnt;
1293
1294         dll_op = event->details.operation_finished.op_cls;
1295         GNUNET_CONTAINER_DLL_remove (dll_op_head, dll_op_tail, dll_op);
1296         GNUNET_free (dll_op);
1297         op = event->details.operation_finished.operation;
1298         if (NULL != event->details.operation_finished.emsg)
1299         {
1300           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1301                _("An operation has failed while starting slaves\n"));
1302           GNUNET_TESTBED_operation_done (op);
1303           if (GNUNET_SCHEDULER_NO_TASK != abort_task)
1304             GNUNET_SCHEDULER_cancel (abort_task);
1305           abort_task = GNUNET_SCHEDULER_add_now (&do_abort, (void*) __LINE__);
1306           return;
1307         }
1308         GNUNET_TESTBED_operation_done (op);
1309         /* Proceed to start peers */
1310         if (++slaves_started == num_hosts - 1)
1311         {
1312           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1313                       "All slaves started successfully\n");
1314
1315           state = STATE_PEERS_CREATING;
1316           prof_start_time = GNUNET_TIME_absolute_get ();
1317
1318           if (-1 == (ret = GNUNET_DISK_directory_scan (policy_dir,
1319                                                        NULL,
1320                                                        NULL)))
1321           {
1322             GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1323                         _("No files found in `%s'\n"),
1324                         policy_dir);
1325             GNUNET_SCHEDULER_shutdown ();
1326             return;
1327           }
1328           num_peers = (unsigned int) ret;
1329           peers = GNUNET_malloc (sizeof (struct RegexPeer) * num_peers);
1330
1331           /* Initialize peers */
1332           for (peer_cnt = 0; peer_cnt < num_peers; peer_cnt++)
1333           {
1334             struct RegexPeer *peer = &peers[peer_cnt];
1335             peer->id = peer_cnt;
1336             peer->policy_file = NULL;
1337             /* Do not start peers on hosts[0] (master controller) */
1338             peer->host_handle = hosts[1 + (peer_cnt % (num_hosts -1))];
1339             peer->dht_handle = NULL;
1340             peer->search_handle = NULL;
1341             peer->stats_handle = NULL;
1342             peer->stats_op_handle = NULL;
1343             peer->search_str = NULL;
1344             peer->search_str_matched = GNUNET_NO;
1345           }
1346
1347           GNUNET_DISK_directory_scan (policy_dir,
1348                                       &policy_filename_cb,
1349                                       NULL);
1350         }
1351       }
1352       break;
1353     default:
1354       GNUNET_assert (0);
1355     }
1356     break;
1357   case STATE_PEERS_STARTING:
1358     switch (event->type)
1359     {
1360     case GNUNET_TESTBED_ET_OPERATION_FINISHED:
1361       /* Control reaches here when peer start fails */
1362     case GNUNET_TESTBED_ET_PEER_START:
1363       /* we handle peer starts in peer_churn_cb */
1364       break;
1365     default:
1366       GNUNET_assert (0);
1367     }
1368     break;
1369   case STATE_PEERS_LINKING:
1370    switch (event->type)
1371    {
1372      static unsigned int established_links;
1373    case GNUNET_TESTBED_ET_OPERATION_FINISHED:
1374      /* Control reaches here when a peer linking operation fails */
1375      if (NULL != event->details.operation_finished.emsg)
1376      {
1377        GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1378                    _("An operation has failed while linking\n"));
1379        printf ("F");
1380        fflush (stdout);
1381        retry_links++;
1382      }
1383      /* We do no retries, consider this link as established */
1384      /* break; */
1385    case GNUNET_TESTBED_ET_CONNECT:
1386    {
1387      char output_buffer[512];
1388      size_t size;
1389
1390      if (0 == established_links)
1391        printf ("Establishing links .");
1392      else
1393      {
1394        printf (".");
1395        fflush (stdout);
1396      }
1397      if (++established_links == num_links)
1398      {
1399        fflush (stdout);
1400        prof_time = GNUNET_TIME_absolute_get_duration (prof_start_time);
1401        GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1402                    "%u links established in %s\n",
1403                    num_links,
1404                    GNUNET_STRINGS_relative_time_to_string (prof_time, GNUNET_NO));
1405        result = GNUNET_OK;
1406        GNUNET_free (peer_handles);
1407
1408        if (NULL != data_file)
1409        {
1410          size =
1411            GNUNET_snprintf (output_buffer,
1412                             sizeof (output_buffer),
1413                             "# of peers: %u\n# of links established: %u\n"
1414                             "Time to establish links: %s\nLinking failures: %u\n"
1415                             "path compression length: %u\n# of search strings: %u\n",
1416                             num_peers,
1417                             (established_links - cont_fails),
1418                             GNUNET_STRINGS_relative_time_to_string (prof_time, GNUNET_NO),
1419                             cont_fails,
1420                             max_path_compression,
1421                             num_search_strings);
1422
1423          if (size != GNUNET_DISK_file_write (data_file, output_buffer, size))
1424            GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Unable to write to file!\n");
1425        }
1426
1427        printf ("\nWaiting %s before starting to search.\n",
1428                GNUNET_STRINGS_relative_time_to_string (search_delay, GNUNET_YES));
1429        fflush (stdout);
1430
1431        GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1432                    "Waiting %s before starting to search.\n",
1433                    GNUNET_STRINGS_relative_time_to_string (search_delay, GNUNET_NO));
1434
1435        state = STATE_SEARCH_REGEX;
1436
1437        search_task = GNUNET_SCHEDULER_add_delayed (search_delay,
1438                                                    &do_connect_by_string, NULL);
1439      }
1440    }
1441    break;
1442    default:
1443      GNUNET_assert (0);
1444    }
1445    break;
1446   case STATE_SEARCH_REGEX:
1447   {
1448     /* Handled in service connect callback */
1449     break;
1450   }
1451   default:
1452     switch (state)
1453     {
1454     case STATE_PEERS_CREATING:
1455       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Failed to create peer\n");
1456       break;
1457     default:
1458       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1459                   "Unexpected controller_cb with state %i!\n", state);
1460     }
1461     GNUNET_assert (0);
1462   }
1463 }
1464
1465
1466 /**
1467  * Task to register all hosts available in the global host list.
1468  *
1469  * @param cls NULL
1470  * @param tc the scheduler task context
1471  */
1472 static void
1473 register_hosts (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1474
1475
1476 /**
1477  * Callback which will be called to after a host registration succeeded or failed
1478  *
1479  * @param cls the closure
1480  * @param emsg the error message; NULL if host registration is successful
1481  */
1482 static void
1483 host_registration_completion (void *cls, const char *emsg)
1484 {
1485   reg_handle = NULL;
1486   if (NULL != emsg)
1487   {
1488     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1489                 _("Host registration failed for a host. Error: %s\n"), emsg);
1490     if (GNUNET_SCHEDULER_NO_TASK != abort_task)
1491       GNUNET_SCHEDULER_cancel (abort_task);
1492     abort_task = GNUNET_SCHEDULER_add_now (&do_abort, (void*) __LINE__);
1493     return;
1494   }
1495   register_hosts_task = GNUNET_SCHEDULER_add_now (&register_hosts, NULL);
1496 }
1497
1498
1499 /**
1500  * Task to register all hosts available in the global host list.
1501  *
1502  * @param cls NULL
1503  * @param tc the scheduler task context
1504  */
1505 static void
1506 register_hosts (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1507 {
1508   struct DLLOperation *dll_op;
1509   static unsigned int reg_host;
1510   unsigned int slave;
1511
1512   register_hosts_task = GNUNET_SCHEDULER_NO_TASK;
1513   if (reg_host == num_hosts - 1)
1514   {
1515     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1516                 "All hosts successfully registered\n");
1517     /* Start slaves */
1518     state = STATE_SLAVES_STARTING;
1519     for (slave = 1; slave < num_hosts; slave++)
1520     {
1521       dll_op = GNUNET_malloc (sizeof (struct DLLOperation));
1522       dll_op->op = GNUNET_TESTBED_controller_link (dll_op,
1523                                                    mc,
1524                                                    hosts[slave],
1525                                                    hosts[0],
1526                                                    cfg,
1527                                                    GNUNET_YES);
1528       GNUNET_CONTAINER_DLL_insert_tail (dll_op_head, dll_op_tail, dll_op);
1529     }
1530     return;
1531   }
1532   reg_handle = GNUNET_TESTBED_register_host (mc, hosts[++reg_host],
1533                                              host_registration_completion,
1534                                              NULL);
1535 }
1536
1537
1538 /**
1539  * Callback to signal successfull startup of the controller process.
1540  *
1541  * @param cls the closure from GNUNET_TESTBED_controller_start()
1542  * @param config the configuration with which the controller has been started;
1543  *          NULL if status is not GNUNET_OK
1544  * @param status GNUNET_OK if the startup is successfull; GNUNET_SYSERR if not,
1545  *          GNUNET_TESTBED_controller_stop() shouldn't be called in this case
1546  */
1547 static void
1548 status_cb (void *cls, const struct GNUNET_CONFIGURATION_Handle *config, int status)
1549 {
1550   if (GNUNET_SCHEDULER_NO_TASK != abort_task)
1551     GNUNET_SCHEDULER_cancel (abort_task);
1552   if (GNUNET_OK != status)
1553   {
1554     mc_proc = NULL;
1555     printf("CRAPPP\n");
1556     abort_task = GNUNET_SCHEDULER_add_now (&do_abort, (void*) __LINE__);
1557     return;
1558   }
1559   event_mask = 0;
1560   event_mask |= (1LL << GNUNET_TESTBED_ET_PEER_START);
1561   event_mask |= (1LL << GNUNET_TESTBED_ET_PEER_STOP);
1562   event_mask |= (1LL << GNUNET_TESTBED_ET_CONNECT);
1563   event_mask |= (1LL << GNUNET_TESTBED_ET_DISCONNECT);
1564   event_mask |= (1LL << GNUNET_TESTBED_ET_OPERATION_FINISHED);
1565   mc = GNUNET_TESTBED_controller_connect (config, hosts[0], event_mask,
1566                                           &controller_event_cb, NULL);
1567   if (NULL == mc)
1568   {
1569     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1570                 _("Unable to connect to master controller -- Check config\n"));
1571     abort_task = GNUNET_SCHEDULER_add_now (&do_abort, (void*) __LINE__);
1572     return;
1573   }
1574   register_hosts_task = GNUNET_SCHEDULER_add_now (&register_hosts, NULL);
1575   abort_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1576                                              &do_abort, (void*) __LINE__);
1577 }
1578
1579
1580 /**
1581  * Load search strings from given filename. One search string per line.
1582  *
1583  * @param filename filename of the file containing the search strings.
1584  * @param strings set of strings loaded from file. Caller needs to free this
1585  *                if number returned is greater than zero.
1586  * @param limit upper limit on the number of strings read from the file
1587  * @return number of strings found in the file. GNUNET_SYSERR on error.
1588  */
1589 static int
1590 load_search_strings (const char *filename, char ***strings, unsigned int limit)
1591 {
1592   char *data;
1593   char *buf;
1594   uint64_t filesize;
1595   unsigned int offset;
1596   int str_cnt;
1597   unsigned int i;
1598
1599   if (NULL == filename)
1600   {
1601     return GNUNET_SYSERR;
1602   }
1603
1604   if (GNUNET_YES != GNUNET_DISK_file_test (filename))
1605   {
1606     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1607                 "Could not find search strings file %s\n", filename);
1608     return GNUNET_SYSERR;
1609   }
1610   if (GNUNET_OK != GNUNET_DISK_file_size (filename, &filesize, GNUNET_YES, GNUNET_YES))
1611     filesize = 0;
1612   if (0 == filesize)
1613   {
1614     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Search strings file %s is empty.\n", filename);
1615     return GNUNET_SYSERR;
1616   }
1617   data = GNUNET_malloc (filesize);
1618   if (filesize != GNUNET_DISK_fn_read (filename, data, filesize))
1619   {
1620     GNUNET_free (data);
1621     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Could not read search strings file %s.\n",
1622          filename);
1623     return GNUNET_SYSERR;
1624   }
1625   buf = data;
1626   offset = 0;
1627   str_cnt = 0;
1628   while (offset < (filesize - 1) && str_cnt < limit)
1629   {
1630     offset++;
1631     if (((data[offset] == '\n')) && (buf != &data[offset]))
1632     {
1633       data[offset] = '\0';
1634       str_cnt++;
1635       buf = &data[offset + 1];
1636     }
1637     else if ((data[offset] == '\n') || (data[offset] == '\0'))
1638       buf = &data[offset + 1];
1639   }
1640   *strings = GNUNET_malloc (sizeof (char *) * str_cnt);
1641   offset = 0;
1642   for (i = 0; i < str_cnt; i++)
1643   {
1644     GNUNET_asprintf (&(*strings)[i], "%s%s", regex_prefix, &data[offset]);
1645     offset += strlen (&data[offset]) + 1;
1646   }
1647   GNUNET_free (data);
1648   return str_cnt;
1649 }
1650
1651
1652 /**
1653  * Callbacks of this type are called by GNUNET_TESTBED_is_host_habitable to
1654  * inform whether the given host is habitable or not. The Handle returned by
1655  * GNUNET_TESTBED_is_host_habitable() is invalid after this callback is called
1656  *
1657  * @param cls NULL
1658  * @param host the host whose status is being reported; will be NULL if the host
1659  *          given to GNUNET_TESTBED_is_host_habitable() is NULL
1660  * @param status GNUNET_YES if it is habitable; GNUNET_NO if not
1661  */
1662 static void 
1663 host_habitable_cb (void *cls, const struct GNUNET_TESTBED_Host *host, int status)
1664 {
1665   struct GNUNET_TESTBED_HostHabitableCheckHandle **hc_handle = cls;
1666   static unsigned int hosts_checked;
1667
1668   *hc_handle = NULL;
1669   if (GNUNET_NO == status)
1670   {
1671     if ((NULL != host) && (NULL != GNUNET_TESTBED_host_get_hostname (host)))
1672       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Host %s cannot start testbed\n"),
1673                   GNUNET_TESTBED_host_get_hostname (host));
1674     else
1675       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Testbed cannot be started on localhost\n"));
1676     GNUNET_SCHEDULER_cancel (abort_task);
1677     abort_task = GNUNET_SCHEDULER_add_now (&do_abort, (void*) __LINE__);
1678     return;
1679   }
1680   hosts_checked++;
1681   /* printf (_("\rChecked %u hosts"), hosts_checked); */
1682   /* fflush (stdout); */
1683   if (hosts_checked < num_hosts)
1684     return;
1685   /* printf (_("\nAll hosts can start testbed. Creating peers\n")); */
1686   GNUNET_free (hc_handles);
1687   hc_handles = NULL;
1688   mc_proc = 
1689       GNUNET_TESTBED_controller_start (GNUNET_TESTBED_host_get_hostname
1690                                        (hosts[0]),
1691                                        hosts[0],
1692                                        cfg,
1693                                        status_cb,
1694                                        NULL);
1695 }
1696
1697
1698 /**
1699  * Main function that will be run by the scheduler.
1700  *
1701  * @param cls closure
1702  * @param args remaining command-line arguments
1703  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
1704  * @param config configuration
1705  */
1706 static void
1707 run (void *cls, char *const *args, const char *cfgfile,
1708      const struct GNUNET_CONFIGURATION_Handle *config)
1709 {
1710   unsigned int nhost;
1711   unsigned int nsearchstrs;
1712
1713   if (NULL == args[0])
1714   {
1715     fprintf (stderr, _("No hosts-file specified on command line. Exiting.\n"));
1716     return;
1717   }
1718   if (NULL == args[1])
1719   {
1720     fprintf (stderr, _("No policy directory specified on command line. Exiting.\n"));
1721     return;
1722   }
1723   num_hosts = GNUNET_TESTBED_hosts_load_from_file (args[0], &hosts);
1724   if (0 == num_hosts)
1725   {
1726     fprintf (stderr, _("No hosts loaded. Need at least one host\n"));
1727     return;
1728   }
1729   printf (_("Checking whether given hosts can start testbed. Please wait\n"));
1730   hc_handles = GNUNET_malloc (sizeof (struct
1731                                       GNUNET_TESTBED_HostHabitableCheckHandle *) 
1732                               * num_hosts);
1733   for (nhost = 0; nhost < num_hosts; nhost++)
1734   {    
1735     if (NULL == (hc_handles[nhost] = GNUNET_TESTBED_is_host_habitable (hosts[nhost], config,
1736                                                                        &host_habitable_cb,
1737                                                                        &hc_handles[nhost])))
1738     {
1739       GNUNET_break (0);
1740       for (nhost = 0; nhost < num_hosts; nhost++)
1741         if (NULL != hc_handles[nhost])
1742           GNUNET_TESTBED_is_host_habitable_cancel (hc_handles[nhost]);
1743       GNUNET_free (hc_handles);
1744       hc_handles = NULL;
1745       break;
1746     }
1747   }
1748   if (num_hosts != nhost)
1749   {
1750     fprintf (stderr, _("Exiting\n"));
1751     shutdown_task = GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1752     return;
1753   }
1754   if (NULL == config)
1755   {
1756     fprintf (stderr, _("No configuration file given. Exiting\n"));
1757     shutdown_task = GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1758     return;
1759   }
1760
1761   if (GNUNET_OK !=
1762       GNUNET_CONFIGURATION_get_value_string (config, "REGEXPROFILER", "REGEX_PREFIX",
1763                                              &regex_prefix))
1764   {
1765     fprintf (stderr, _("Configuration option (regex_prefix) missing. Exiting\n"));
1766     shutdown_task = GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1767     return;
1768   }
1769
1770   if ( (NULL != data_filename) &&
1771        (NULL == (data_file =
1772                  GNUNET_DISK_file_open (data_filename,
1773                                         GNUNET_DISK_OPEN_READWRITE |
1774                                         GNUNET_DISK_OPEN_TRUNCATE |
1775                                         GNUNET_DISK_OPEN_CREATE,
1776                                         GNUNET_DISK_PERM_USER_READ |
1777                                         GNUNET_DISK_PERM_USER_WRITE))) )
1778     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
1779                               "open",
1780                               data_filename);
1781   if (GNUNET_YES != GNUNET_DISK_directory_test (args[1], GNUNET_YES))
1782   {
1783     fprintf (stderr, _("Specified policies directory does not exist. Exiting.\n"));
1784     shutdown_task = GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1785     return;
1786   }
1787   policy_dir = args[1];
1788   if (GNUNET_YES != GNUNET_DISK_file_test (args[2]))
1789   {
1790     fprintf (stderr, _("No search strings file given. Exiting.\n"));
1791     shutdown_task = GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1792     return;
1793   }
1794   nsearchstrs = load_search_strings (args[2], &search_strings, num_search_strings);
1795   if (num_search_strings != nsearchstrs)
1796   {
1797     num_search_strings = nsearchstrs;
1798     fprintf (stderr, _("Error loading search strings. Given file does not contain enough strings. Exiting.\n"));
1799     shutdown_task = GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1800     return;
1801   }
1802   if (0 >= num_search_strings || NULL == search_strings)
1803   {
1804     fprintf (stderr, _("Error loading search strings. Exiting.\n"));
1805     shutdown_task = GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1806     return;
1807   }
1808   unsigned int i;
1809   for (i = 0; i < num_search_strings; i++)
1810     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "search string: %s\n", search_strings[i]);
1811   cfg = GNUNET_CONFIGURATION_dup (config);
1812   abort_task =
1813       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
1814                                     (GNUNET_TIME_UNIT_SECONDS, 5), &do_abort,
1815                                     (void*) __LINE__);
1816 }
1817
1818
1819 /**
1820  * Main function.
1821  *
1822  * @param argc argument count
1823  * @param argv argument values
1824  * @return 0 on success
1825  */
1826 int
1827 main (int argc, char *const *argv)
1828 {
1829   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
1830     {'d', "details", "FILENAME",
1831      gettext_noop ("name of the file for writing statistics"),
1832      1, &GNUNET_GETOPT_set_string, &data_filename},
1833     {'n', "num-links", "COUNT",
1834       gettext_noop ("create COUNT number of random links between peers"),
1835       GNUNET_YES, &GNUNET_GETOPT_set_uint, &linking_factor },
1836     {'t', "matching-timeout", "TIMEOUT",
1837       gettext_noop ("wait TIMEOUT before considering a string match as failed"),
1838       GNUNET_YES, &GNUNET_GETOPT_set_relative_time, &search_timeout },
1839     {'s', "search-delay", "DELAY",
1840       gettext_noop ("wait DELAY before starting string search"),
1841       GNUNET_YES, &GNUNET_GETOPT_set_relative_time, &search_delay },
1842     {'a', "num-search-strings", "COUNT",
1843       gettext_noop ("number of search strings to read from search strings file"),
1844       GNUNET_YES, &GNUNET_GETOPT_set_uint, &num_search_strings },
1845     {'p', "max-path-compression", "MAX_PATH_COMPRESSION",
1846      gettext_noop ("maximum path compression length"),
1847      1, &GNUNET_GETOPT_set_uint, &max_path_compression},
1848     {'i', "no-distributed-search", "",
1849      gettext_noop ("if this option is set, only one peer is responsible for searching all strings"),
1850      0, &GNUNET_GETOPT_set_one, &no_distributed_search},
1851     GNUNET_GETOPT_OPTION_END
1852   };
1853   int ret;
1854
1855   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
1856     return 2;
1857
1858   result = GNUNET_SYSERR;
1859   ret =
1860       GNUNET_PROGRAM_run (argc, argv, "gnunet-regex-profiler [OPTIONS] hosts-file policy-dir search-strings-file",
1861                           _("Profiler for regex/mesh"),
1862                           options, &run, NULL);
1863
1864   if (GNUNET_OK != ret)
1865     return ret;
1866   if (GNUNET_OK != result)
1867     return 1;
1868   return 0;
1869 }