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