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