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