c0433230ee82a188f9eaf6205980ef0f75fb97f8
[oweals/gnunet.git] / src / regex / gnunet-regex-profiler.c
1 /*
2      This file is part of GNUnet.
3      (C) 2011 - 2013 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file regex/gnunet-regex-profiler.c
23  * @brief Regex profiler for testing distributed regex use.
24  * @author Bartlomiej Polot
25  * @author Maximilian Szengel
26  *
27  */
28
29 #include <string.h>
30
31 #include "platform.h"
32 #include "gnunet_applications.h"
33 #include "gnunet_util_lib.h"
34 #include "gnunet_regex_lib.h"
35 #include "gnunet_arm_service.h"
36 #include "gnunet_dht_service.h"
37 #include "gnunet_testbed_service.h"
38
39 #define FIND_TIMEOUT \
40         GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 90)
41 #define SEARCHES_IN_PARALLEL 5
42
43 /**
44  * DLL of operations
45  */
46 struct DLLOperation
47 {
48   /**
49    * The testbed operation handle
50    */
51   struct GNUNET_TESTBED_Operation *op;
52
53   /**
54    * Closure
55    */
56   void *cls;
57
58   /**
59    * The next pointer for DLL
60    */
61   struct DLLOperation *next;
62
63   /**
64    * The prev pointer for DLL
65    */
66   struct DLLOperation *prev;
67 };
68
69
70 /**
71  * Available states during profiling
72  */
73 enum State
74 {
75   /**
76    * Initial state
77    */
78   STATE_INIT = 0,
79
80   /**
81    * Starting slaves
82    */
83   STATE_SLAVES_STARTING,
84
85   /**
86    * Creating peers
87    */
88   STATE_PEERS_CREATING,
89
90   /**
91    * Starting peers
92    */
93   STATE_PEERS_STARTING,
94
95   /**
96    * Linking peers
97    */
98   STATE_PEERS_LINKING,
99
100   /**
101    * Matching strings against announced regexes
102    */
103   STATE_SEARCH_REGEX,
104
105   /**
106    * Destroying peers; we can do this as the controller takes care of stopping a
107    * peer if it is running
108    */
109   STATE_PEERS_DESTROYING
110 };
111
112
113 /**
114  * Peer handles.
115  */
116 struct RegexPeer
117 {
118   /**
119    * Peer id.
120    */
121   unsigned int id;
122
123   /**
124    * Peer configuration handle.
125    */
126   struct GNUNET_CONFIGURATION_Handle *cfg;
127
128   /**
129    * The actual testbed peer handle.
130    */
131   struct GNUNET_TESTBED_Peer *peer_handle;
132
133   /**
134    * Filename of the peer's policy file.
135    */
136   char *policy_file;
137
138   /**
139    * Peer's search string.
140    */
141   const char *search_str;
142
143   /**
144    * Set to GNUNET_YES if the peer successfully matched the above
145    * search string. GNUNET_NO if the string could not be matched
146    * during the profiler run. GNUNET_SYSERR if the string matching
147    * timed out. Undefined if search_str is NULL
148    */
149   int search_str_matched;
150
151   /**
152    * Peer's DHT handle.
153    */
154   struct GNUNET_DHT_Handle *dht_handle;
155
156   /**
157    * Handle to a running regex search.
158    */
159    struct GNUNET_REGEX_search_handle *search_handle;
160
161   /**
162    * Testbed operation handle for DHT.
163    */
164   struct GNUNET_TESTBED_Operation *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    * Operation timeout
183    */
184   GNUNET_SCHEDULER_TaskIdentifier timeout;
185
186   /**
187    * Deamon start
188    */
189   struct GNUNET_TESTBED_Operation *daemon_op;
190 };
191
192
193 /**
194  * The array of peers; we fill this as the peers are given to us by the testbed
195  */
196 static struct RegexPeer *peers;
197
198 /**
199  * Host registration handle
200  */
201 static struct GNUNET_TESTBED_HostRegistrationHandle *reg_handle;
202
203 /**
204  * Handle to the master controller process
205  */
206 static struct GNUNET_TESTBED_ControllerProc *mc_proc;
207
208 /**
209  * Handle to the master controller
210  */
211 static struct GNUNET_TESTBED_Controller *mc;
212
213 /**
214  * Handle to global configuration
215  */
216 static struct GNUNET_CONFIGURATION_Handle *cfg;
217
218 /**
219  * Abort task identifier
220  */
221 static GNUNET_SCHEDULER_TaskIdentifier abort_task;
222
223 /**
224  * Shutdown task identifier
225  */
226 static GNUNET_SCHEDULER_TaskIdentifier shutdown_task;
227
228 /**
229  * Host registration task identifier
230  */
231 static GNUNET_SCHEDULER_TaskIdentifier register_hosts_task;
232
233 /**
234  * Global event mask for all testbed events
235  */
236 static uint64_t event_mask;
237
238 /**
239  * The starting time of a profiling step
240  */
241 static struct GNUNET_TIME_Absolute prof_start_time;
242
243 /**
244  * Duration profiling step has taken
245  */
246 static struct GNUNET_TIME_Relative prof_time;
247
248 /**
249  * Number of peers to be started by the profiler
250  */
251 static unsigned int num_peers;
252
253 /**
254  * Factor of number of links. num_links = num_peers * linking_factor.
255  */
256 static unsigned int linking_factor;
257
258 /**
259  * Global testing status
260  */
261 static int result;
262
263 /**
264  * current state of profiling
265  */
266 enum State state;
267
268 /**
269  * Folder where policy files are stored.
270  */
271 static char * policy_dir;
272
273 /**
274  * Search strings.
275  */
276 static char **search_strings;
277
278 /**
279  * Number of search strings.
280  */
281 static int num_search_strings;
282
283 /**
284  * How many searches are running in parallel
285  */
286 static unsigned int parallel_searches;
287
288 /**
289  * Number of peers found with search strings.
290  */
291 static unsigned int peers_found;
292
293 /**
294  * Index of peer to start next announce/search.
295  */
296 static unsigned int next_search;
297
298 /**
299  * Search timeout task identifier.
300  */
301 static GNUNET_SCHEDULER_TaskIdentifier search_timeout_task;
302
303 /**
304  * Search timeout in seconds.
305  */
306 static struct GNUNET_TIME_Relative search_timeout_time = { 60000 };
307
308 /**
309  * How long do we wait before starting the search?
310  * Default: 1 m.
311  */
312 static struct GNUNET_TIME_Relative search_delay = { 60000 };
313
314 /**
315  * File to log statistics to.
316  */
317 static struct GNUNET_DISK_FileHandle *data_file;
318
319 /**
320  * Filename to log statistics to.
321  */
322 static char *data_filename;
323
324 /**
325  * Maximal path compression length.
326  */
327 static unsigned int max_path_compression;
328
329 /**
330  * Prefix used for regex announcing. We need to prefix the search
331  * strings with it, in order to find something.
332  */
333 static char * regex_prefix;
334
335 /**
336  * What's the maximum regex reannounce period.
337  */
338 static struct GNUNET_TIME_Relative reannounce_period_max;
339
340
341 /******************************************************************************/
342 /******************************  DECLARATIONS  ********************************/
343 /******************************************************************************/
344
345 /**
346  * DHT connect callback.
347  *
348  * @param cls internal peer id.
349  * @param op operation handle.
350  * @param ca_result connect adapter result.
351  * @param emsg error message.
352  */
353 static void
354 dht_connect_cb (void *cls, struct GNUNET_TESTBED_Operation *op,
355                 void *ca_result, const char *emsg);
356
357 /**
358  * DHT connect adapter.
359  *
360  * @param cls not used.
361  * @param cfg configuration handle.
362  *
363  * @return
364  */
365 static void *
366 dht_ca (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg);
367
368
369 /**
370  * Adapter function called to destroy a connection to
371  * the DHT service
372  *
373  * @param cls closure
374  * @param op_result service handle returned from the connect adapter
375  */
376 static void
377 dht_da (void *cls, void *op_result);
378
379
380 /**
381  * Function called by testbed once we are connected to stats
382  * service. Get the statistics for the services of interest.
383  *
384  * @param cls the 'struct RegexPeer' for which we connected to stats
385  * @param op connect operation handle
386  * @param ca_result handle to stats service
387  * @param emsg error message on failure
388  */
389 static void
390 stats_connect_cb (void *cls,
391                   struct GNUNET_TESTBED_Operation *op,
392                   void *ca_result,
393                   const char *emsg);
394
395
396 /**
397  * Task to collect all statistics from s, will shutdown the
398  * profiler, when done.
399  *
400  * @param cls NULL
401  * @param tc the task context
402  */
403 static void
404 do_collect_stats (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
405
406
407 /**
408  * Start announcing the next regex in the DHT.
409  *
410  * @param cls Index of the next peer in the peers array.
411  * @param tc TaskContext.
412  */
413 static void
414 announce_next_regex (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
415
416
417 /******************************************************************************/
418 /********************************  SHUTDOWN  **********************************/
419 /******************************************************************************/
420
421
422 /**
423  * Shutdown nicely
424  *
425  * @param cls NULL
426  * @param tc the task context
427  */
428 static void
429 do_shutdown (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
430 {
431   struct RegexPeer *peer;
432   unsigned int peer_cnt;
433   unsigned int search_str_cnt;
434   char output_buffer[512];
435   size_t size;
436
437   shutdown_task = GNUNET_SCHEDULER_NO_TASK;
438   if (GNUNET_SCHEDULER_NO_TASK != abort_task)
439     GNUNET_SCHEDULER_cancel (abort_task);
440   if (GNUNET_SCHEDULER_NO_TASK != register_hosts_task)
441     GNUNET_SCHEDULER_cancel (register_hosts_task);
442
443   for (peer_cnt = 0; peer_cnt < num_peers; peer_cnt++)
444   {
445     peer = &peers[peer_cnt];
446
447     if (GNUNET_YES != peer->search_str_matched && NULL != data_file)
448     {
449       prof_time = GNUNET_TIME_absolute_get_duration (peer->prof_start_time);
450       size =
451         GNUNET_snprintf (output_buffer,
452                          sizeof (output_buffer),
453                          "%p Search string not found: %s (%d)\n%p On peer: %u (%p)\n%p With policy file: %s\n%p After: %s\n",
454                          peer, peer->search_str, peer->search_str_matched,
455                          peer, peer->id, peer,
456                          peer, peer->policy_file,
457                          peer,
458                          GNUNET_STRINGS_relative_time_to_string (prof_time,
459                                                                  GNUNET_NO));
460       if (size != GNUNET_DISK_file_write (data_file, output_buffer, size))
461         GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Unable to write to file!\n");
462     }
463
464     if (NULL != peers[peer_cnt].op_handle)
465       GNUNET_TESTBED_operation_done (peers[peer_cnt].op_handle);
466     if (NULL != peers[peer_cnt].stats_op_handle)
467       GNUNET_TESTBED_operation_done (peers[peer_cnt].stats_op_handle);
468   }
469
470   if (NULL != data_file)
471     GNUNET_DISK_file_close (data_file);
472
473   for (search_str_cnt = 0;
474        search_str_cnt < num_search_strings && NULL != search_strings;
475        search_str_cnt++)
476   {
477     GNUNET_free_non_null (search_strings[search_str_cnt]);
478   }
479   GNUNET_free_non_null (search_strings);
480
481   if (NULL != reg_handle)
482     GNUNET_TESTBED_cancel_registration (reg_handle);
483
484   if (NULL != mc)
485     GNUNET_TESTBED_controller_disconnect (mc);
486   if (NULL != mc_proc)
487     GNUNET_TESTBED_controller_stop (mc_proc);
488   if (NULL != cfg)
489     GNUNET_CONFIGURATION_destroy (cfg);
490
491   GNUNET_SCHEDULER_shutdown (); /* Stop scheduler to shutdown testbed run */
492 }
493
494
495 /**
496  * abort task to run on test timed out
497  *
498  * @param cls NULL
499  * @param tc the task context
500  */
501 static void
502 do_abort (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
503 {
504   unsigned long i = (unsigned long) cls;
505
506   GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Aborting %lu...\n", i);
507   abort_task = GNUNET_SCHEDULER_NO_TASK;
508   result = GNUNET_SYSERR;
509   if (GNUNET_SCHEDULER_NO_TASK != shutdown_task)
510     GNUNET_SCHEDULER_cancel (shutdown_task);
511   shutdown_task = GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
512 }
513
514
515 /******************************************************************************/
516 /*********************  STATISTICS SERVICE CONNECTIONS  ***********************/
517 /******************************************************************************/
518
519 /**
520  * Adapter function called to establish a connection to
521  * statistics service.
522  *
523  * @param cls closure
524  * @param cfg configuration of the peer to connect to; will be available until
525  *          GNUNET_TESTBED_operation_done() is called on the operation returned
526  *          from GNUNET_TESTBED_service_connect()
527  * @return service handle to return in 'op_result', NULL on error
528  */
529 static void *
530 stats_ca (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg)
531 {
532   return GNUNET_STATISTICS_create ("<driver>", cfg);
533 }
534
535
536 /**
537  * Adapter function called to destroy a connection to
538  * statistics service.
539  *
540  * @param cls closure
541  * @param op_result service handle returned from the connect adapter
542  */
543 static void
544 stats_da (void *cls, void *op_result)
545 {
546   struct RegexPeer *peer = cls;
547
548   GNUNET_assert (op_result == peer->stats_handle);
549
550   GNUNET_STATISTICS_destroy (peer->stats_handle, GNUNET_NO);
551   peer->stats_handle = NULL;
552 }
553
554
555 /**
556  * Process statistic values. Write all values to global 'data_file', if present.
557  *
558  * @param cls closure
559  * @param subsystem name of subsystem that created the statistic
560  * @param name the name of the datum
561  * @param value the current value
562  * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
563  * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
564  */
565 static int
566 stats_iterator (void *cls, const char *subsystem, const char *name,
567                 uint64_t value, int is_persistent)
568 {
569   struct RegexPeer *peer = cls;
570   char output_buffer[512];
571   size_t size;
572
573   if (NULL == data_file)
574   {
575     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
576                 "%p -> %s [%s]: %llu\n",
577                 peer, subsystem, name, value);
578     return GNUNET_OK;
579   }
580   size =
581     GNUNET_snprintf (output_buffer,
582                      sizeof (output_buffer),
583                      "%p [%s] %llu %s\n",
584                      peer,
585                      subsystem, value, name);
586   if (size != GNUNET_DISK_file_write (data_file, output_buffer, size))
587     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Unable to write to file!\n");
588
589   return GNUNET_OK;
590 }
591
592
593 /**
594  * Stats callback. Finish the stats testbed operation and when all stats have
595  * been iterated, shutdown the profiler.
596  *
597  * @param cls closure
598  * @param success GNUNET_OK if statistics were
599  *        successfully obtained, GNUNET_SYSERR if not.
600  */
601 static void
602 stats_cb (void *cls,
603           int success)
604 {
605   static unsigned int peer_cnt;
606   struct RegexPeer *peer = cls;
607
608   if (GNUNET_OK != success)
609   {
610     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
611                 "Getting statistics for peer %u failed!\n",
612                 peer->id);
613     return;
614   }
615
616   GNUNET_assert (NULL != peer->stats_op_handle);
617
618   GNUNET_TESTBED_operation_done (peer->stats_op_handle);
619   peer->stats_op_handle = NULL;
620
621   peer_cnt++;
622   peer = &peers[peer_cnt];
623
624   if (peer_cnt == num_peers)
625   {
626     struct GNUNET_TIME_Relative delay = { 100 };
627     shutdown_task = GNUNET_SCHEDULER_add_delayed (delay, &do_shutdown, NULL);
628   }
629   else
630   {
631     peer->stats_op_handle =
632       GNUNET_TESTBED_service_connect (NULL,
633                                       peer->peer_handle,
634                                       "statistics",
635                                       &stats_connect_cb,
636                                       peer,
637                                       &stats_ca,
638                                       &stats_da,
639                                       peer);
640   }
641 }
642
643
644 /**
645  * Function called by testbed once we are connected to stats
646  * service. Get the statistics for the services of interest.
647  *
648  * @param cls the 'struct RegexPeer' for which we connected to stats
649  * @param op connect operation handle
650  * @param ca_result handle to stats service
651  * @param emsg error message on failure
652  */
653 static void
654 stats_connect_cb (void *cls,
655                   struct GNUNET_TESTBED_Operation *op,
656                   void *ca_result,
657                   const char *emsg)
658 {
659   struct RegexPeer *peer = cls;
660
661   if (NULL == ca_result || NULL != emsg)
662   {
663     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
664                 "Failed to connect to statistics service on peer %u: %s\n",
665                 peer->id, emsg);
666
667     peer->stats_handle = NULL;
668     return;
669   }
670
671   peer->stats_handle = ca_result;
672
673   if (NULL == GNUNET_STATISTICS_get (peer->stats_handle, NULL, NULL,
674                                      GNUNET_TIME_UNIT_FOREVER_REL,
675                                      &stats_cb,
676                                      &stats_iterator, peer))
677   {
678     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
679                 "Could not get statistics of peer %u!\n", peer->id);
680   }
681 }
682
683
684 /**
685  * Task to collect all statistics from all peers, will shutdown the
686  * profiler, when done.
687  *
688  * @param cls NULL
689  * @param tc the task context
690  */
691 static void
692 do_collect_stats (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
693 {
694   struct RegexPeer *peer = &peers[0];
695
696   GNUNET_assert (NULL != peer->peer_handle);
697
698   peer->stats_op_handle =
699     GNUNET_TESTBED_service_connect (NULL,
700                                     peer->peer_handle,
701                                     "statistics",
702                                     &stats_connect_cb,
703                                     peer,
704                                     &stats_ca,
705                                     &stats_da,
706                                     peer);
707 }
708
709
710 /******************************************************************************/
711 /************************   REGEX FIND CONNECTIONS   **************************/
712 /******************************************************************************/
713
714
715 /**
716  * Start searching for the next string in the DHT.
717  *
718  * @param cls Index of the next peer in the peers array.
719  * @param tc TaskContext.
720  */
721 static void
722 find_string (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
723
724
725 /**
726  * Method called when we've found a peer that announced a regex
727  * that matches our search string. Now get the statistics.
728  *
729  * @param cls Closure provided in GNUNET_REGEX_search.
730  * @param id Peer providing a regex that matches the string.
731  * @param get_path Path of the get request.
732  * @param get_path_length Lenght of get_path.
733  * @param put_path Path of the put request.
734  * @param put_path_length Length of the put_path.
735  */
736 static void
737 regex_found_handler (void *cls,
738                      const struct GNUNET_PeerIdentity *id,
739                      const struct GNUNET_PeerIdentity *get_path,
740                      unsigned int get_path_length,
741                      const struct GNUNET_PeerIdentity *put_path,
742                      unsigned int put_path_length)
743 {
744   struct RegexPeer *peer = cls;
745   char output_buffer[512];
746   size_t size;
747
748   if (GNUNET_YES == peer->search_str_matched)
749   {
750     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
751                 "String %s on peer %u already matched!\n",
752                 peer->search_str, peer->id);
753     return;
754   }
755
756   peers_found++;
757   parallel_searches--;
758
759   if (GNUNET_SCHEDULER_NO_TASK != peer->timeout)
760   {
761     GNUNET_SCHEDULER_cancel (peer->timeout);
762     peer->timeout = GNUNET_SCHEDULER_NO_TASK;
763     GNUNET_SCHEDULER_add_now (&announce_next_regex, NULL);
764   }
765
766   if (NULL == id)
767   {
768     // FIXME not possible right now
769     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
770                 "String matching timed out for string %s on peer %u (%i/%i)\n",
771                 peer->search_str, peer->id, peers_found, num_search_strings);
772     peer->search_str_matched = GNUNET_SYSERR;
773   }
774   else
775   {
776     prof_time = GNUNET_TIME_absolute_get_duration (peer->prof_start_time);
777
778     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
779                 "String %s found on peer %u after %s (%i/%i) (%u||)\n",
780                 peer->search_str, peer->id,
781                 GNUNET_STRINGS_relative_time_to_string (prof_time, GNUNET_NO),
782                 peers_found, num_search_strings, parallel_searches);
783
784     peer->search_str_matched = GNUNET_YES;
785
786     if (NULL != data_file)
787     {
788       size =
789         GNUNET_snprintf (output_buffer,
790                          sizeof (output_buffer),
791                          "%p Peer: %u\n%p Policy file: %s\n"
792                          "%p Search string: %s\n%p Search duration: %s\n\n",
793                          peer, peer->id,
794                          peer, peer->policy_file,
795                          peer, peer->search_str,
796                          peer,
797                          GNUNET_STRINGS_relative_time_to_string (prof_time,
798                                                                  GNUNET_NO));
799
800       if (size != GNUNET_DISK_file_write (data_file, output_buffer, size))
801         GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Unable to write to file!\n");
802     }
803   }
804
805   GNUNET_TESTBED_operation_done (peer->op_handle);
806   peer->op_handle = NULL;
807
808   if (peers_found == num_search_strings)
809   {
810     prof_time = GNUNET_TIME_absolute_get_duration (prof_start_time);
811     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
812                 "All strings successfully matched in %s\n",
813                 GNUNET_STRINGS_relative_time_to_string (prof_time, GNUNET_NO));
814
815     if (GNUNET_SCHEDULER_NO_TASK != search_timeout_task)
816       GNUNET_SCHEDULER_cancel (search_timeout_task);
817
818     GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Collecting stats and shutting down.\n");
819     GNUNET_SCHEDULER_add_now (&do_collect_stats, NULL);
820   }
821 }
822
823
824 /**
825  * Connect by string timeout task. This will cancel the profiler after the
826  * specified timeout 'search_timeout'.
827  *
828  * @param cls NULL
829  * @param tc the task context
830  */
831 static void
832 search_timeout (void *cls,
833                               const struct GNUNET_SCHEDULER_TaskContext * tc)
834 {
835   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
836               "Finding matches to all strings did not succeed after %s.\n",
837               GNUNET_STRINGS_relative_time_to_string (search_timeout_time,
838                                                       GNUNET_NO));
839   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
840               "Found %i of %i strings\n", peers_found, num_search_strings);
841
842   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
843               "Search timed out after %s."
844               "Collecting stats and shutting down.\n", 
845               GNUNET_STRINGS_relative_time_to_string (search_timeout_time,
846                                                       GNUNET_NO));
847
848   GNUNET_SCHEDULER_add_now (&do_collect_stats, NULL);
849 }
850
851
852 /**
853  * Search timed out. It might still complete in the future,
854  * but we should start another one.
855  *
856  * @param cls Index of the next peer in the peers array.
857  * @param tc TaskContext.
858  */
859 static void
860 find_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
861 {
862   struct RegexPeer *p = cls;
863
864   p->timeout = GNUNET_SCHEDULER_NO_TASK;
865
866   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
867     return;
868   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
869               "Searching for string \"%s\" on peer %d timed out. Starting new search.\n",
870               p->search_str,
871               p->id);
872   GNUNET_SCHEDULER_add_now (&announce_next_regex, NULL);
873 }
874
875
876 /**
877  * Start searching for a string in the DHT.
878  *
879  * @param cls Index of the next peer in the peers array.
880  * @param tc TaskContext.
881  */
882 static void
883 find_string (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
884 {
885   unsigned int search_peer = (unsigned int) (long) cls;
886
887   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) ||
888       search_peer >= num_search_strings)
889     return;
890
891   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
892               "Searching for string \"%s\" on peer %d with file %s (%u||)\n",
893               peers[search_peer].search_str,
894               search_peer,
895               peers[search_peer].policy_file,
896               parallel_searches);
897
898   peers[search_peer].op_handle =
899     GNUNET_TESTBED_service_connect (NULL,
900                                     peers[search_peer].peer_handle,
901                                     "dht",
902                                     &dht_connect_cb,
903                                     &peers[search_peer],
904                                     &dht_ca,
905                                     &dht_da,
906                                     &peers[search_peer]);
907   GNUNET_assert (NULL != peers[search_peer].op_handle);
908   peers[search_peer].timeout = GNUNET_SCHEDULER_add_delayed (FIND_TIMEOUT,
909                                                           &find_timeout,
910                                                           &peers[search_peer]);
911 }
912
913
914
915
916 /**
917  * Callback called when testbed has started the daemon we asked for.
918  *
919  * @param cls NULL
920  * @param op the operation handle
921  * @param emsg NULL on success; otherwise an error description
922  */
923 static void
924 daemon_started (void *cls, struct GNUNET_TESTBED_Operation *op,
925                 const char *emsg)
926 {
927   struct RegexPeer *peer = (struct RegexPeer *) cls;
928   unsigned long search_peer;
929   unsigned int i;
930   unsigned int me;
931
932   GNUNET_TESTBED_operation_done (peer->daemon_op);
933   me = peer - peers;
934   if (NULL != emsg)
935   {
936     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
937                 "Failed to start/stop daemon at peer %u: %s\n", me, emsg);
938     GNUNET_abort ();
939   }
940
941   /* Find a peer to look for a string matching the regex announced */
942   search_peer = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
943                                           num_peers);
944   for (i = 0; peers[search_peer].search_str != NULL; i++)
945   {
946     search_peer = (search_peer + 1) % num_peers;
947     if (i > num_peers)
948       GNUNET_abort (); /* we ran out of peers, must be a bug */
949   }
950   peers[search_peer].search_str = search_strings[me];
951   peers[search_peer].search_str_matched = GNUNET_NO;
952   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply(
953                                   reannounce_period_max,
954                                   2),
955                                 &find_string,
956                                 (void *) search_peer);
957   if (next_search >= num_peers &&
958       GNUNET_SCHEDULER_NO_TASK == search_timeout_task)
959   {
960     GNUNET_log (GNUNET_ERROR_TYPE_INFO, "All daemons started.\n");
961     /* FIXME start GLOBAL timeout to abort experiment */
962     search_timeout_task = GNUNET_SCHEDULER_add_delayed (search_timeout_time,
963                                                         &search_timeout,
964                                                         NULL);
965   }
966 }
967
968
969 /**
970  * Task to start the daemons on each peer so that the regexes are announced
971  * into the DHT.
972  *
973  * @param cls NULL
974  * @param tc the task context
975  */
976 static void
977 do_announce (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
978 {
979   unsigned int i;
980
981   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Starting announce.\n");
982
983   for (i = 0; i < SEARCHES_IN_PARALLEL; i++)
984   {
985     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
986                 "  scheduling announce %u\n",
987                 i);
988     (void) GNUNET_SCHEDULER_add_now (&announce_next_regex, NULL);
989   }
990 }
991
992
993 /**
994  * Start announcing the next regex in the DHT.
995  *
996  * @param cls Closure (unused).
997  * @param tc TaskContext.
998  */
999 static void
1000 announce_next_regex (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1001 {
1002   struct RegexPeer *peer;
1003
1004   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) ||
1005             next_search >= num_peers)
1006     return;
1007
1008   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Starting daemon %u\n", next_search);
1009   peer = &peers[next_search];
1010   peer->daemon_op = 
1011   GNUNET_TESTBED_peer_manage_service (NULL,
1012                                       peer->peer_handle,
1013                                       "regexprofiler",
1014                                       &daemon_started,
1015                                       peer,
1016                                       1);
1017   next_search++;
1018   parallel_searches++;
1019 }
1020
1021 /**
1022  * DHT connect callback. Called when we are connected to the dht service for
1023  * the peer in 'cls'. If successfull we connect to the stats service of this
1024  * peer and then try to match the search string of this peer.
1025  *
1026  * @param cls internal peer id.
1027  * @param op operation handle.
1028  * @param ca_result connect adapter result.
1029  * @param emsg error message.
1030  */
1031 static void
1032 dht_connect_cb (void *cls, struct GNUNET_TESTBED_Operation *op,
1033                 void *ca_result, const char *emsg)
1034 {
1035   struct RegexPeer *peer = (struct RegexPeer *) cls;
1036
1037   if (NULL != emsg || NULL == op || NULL == ca_result)
1038   {
1039     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "DHT connect failed: %s\n", emsg);
1040     GNUNET_abort ();
1041   }
1042
1043   GNUNET_assert (NULL != peer->dht_handle);
1044   GNUNET_assert (peer->op_handle == op);
1045   GNUNET_assert (peer->dht_handle == ca_result);
1046
1047   peer->search_str_matched = GNUNET_NO;
1048   peer->search_handle = GNUNET_REGEX_search (peer->dht_handle,
1049                                              peer->search_str,
1050                                              &regex_found_handler, peer,
1051                                              NULL);
1052   peer->prof_start_time = GNUNET_TIME_absolute_get ();
1053 }
1054
1055
1056 /**
1057  * DHT connect adapter. Opens a connection to the dht service.
1058  *
1059  * @param cls Closure (peer).
1060  * @param cfg Configuration handle.
1061  *
1062  * @return
1063  */
1064 static void *
1065 dht_ca (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg)
1066 {
1067   struct RegexPeer *peer = cls;
1068
1069   peer->dht_handle = GNUNET_DHT_connect (cfg, 32);
1070
1071   return peer->dht_handle;
1072 }
1073
1074
1075 /**
1076  * Adapter function called to destroy a connection to the dht service.
1077  *
1078  * @param cls Closure (peer).
1079  * @param op_result Service handle returned from the connect adapter.
1080  */
1081 static void
1082 dht_da (void *cls, void *op_result)
1083 {
1084   struct RegexPeer *peer = (struct RegexPeer *) cls;
1085
1086   GNUNET_assert (peer->dht_handle == op_result);
1087
1088   if (NULL != peer->search_handle)
1089   {
1090     GNUNET_REGEX_search_cancel (peer->search_handle);
1091     peer->search_handle = NULL;
1092   }
1093
1094   if (NULL != peer->dht_handle)
1095   {
1096     GNUNET_DHT_disconnect (peer->dht_handle);
1097     peer->dht_handle = NULL;
1098   }
1099 }
1100
1101
1102 /**
1103  * Signature of a main function for a testcase.
1104  *
1105  * @param cls NULL
1106  * @param num_peers_ number of peers in 'peers'
1107  * @param peers handle to peers run in the testbed.  NULL upon timeout (see
1108  *          GNUNET_TESTBED_test_run()).
1109  * @param links_succeeded the number of overlay link connection attempts that
1110  *          succeeded
1111  * @param links_failed the number of overlay link connection attempts that
1112  *          failed
1113  */
1114 static void 
1115 test_master (void *cls,
1116              unsigned int num_peers_,
1117              struct GNUNET_TESTBED_Peer **testbed_peers,
1118              unsigned int links_succeeded,
1119              unsigned int links_failed)
1120 {
1121   unsigned int i;
1122
1123   prof_time = GNUNET_TIME_absolute_get_duration (prof_start_time);
1124   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1125               "Testbed started in %s\n",
1126               GNUNET_STRINGS_relative_time_to_string (prof_time, GNUNET_NO));
1127
1128   if (GNUNET_SCHEDULER_NO_TASK != abort_task)
1129   {
1130     GNUNET_SCHEDULER_cancel (abort_task);
1131     abort_task = GNUNET_SCHEDULER_NO_TASK;
1132   }
1133
1134   for (i = 0; i < num_peers; i++)
1135   {
1136   }
1137   GNUNET_SCHEDULER_add_now (&do_announce, NULL);
1138 }
1139
1140
1141 /******************************************************************************/
1142 /***************************  TESTBED PEER SETUP  *****************************/
1143 /******************************************************************************/
1144
1145
1146 /**
1147  * Load search strings from given filename. One search string per line.
1148  *
1149  * @param filename filename of the file containing the search strings.
1150  * @param strings set of strings loaded from file. Caller needs to free this
1151  *                if number returned is greater than zero.
1152  * @param limit upper limit on the number of strings read from the file
1153  * @return number of strings found in the file. GNUNET_SYSERR on error.
1154  */
1155 static int
1156 load_search_strings (const char *filename, char ***strings, unsigned int limit)
1157 {
1158   char *data;
1159   char *buf;
1160   uint64_t filesize;
1161   unsigned int offset;
1162   int str_cnt;
1163   unsigned int i;
1164
1165   if (NULL == filename)
1166   {
1167     return GNUNET_SYSERR;
1168   }
1169
1170   if (GNUNET_YES != GNUNET_DISK_file_test (filename))
1171   {
1172     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1173                 "Could not find search strings file %s\n", filename);
1174     return GNUNET_SYSERR;
1175   }
1176   if (GNUNET_OK != GNUNET_DISK_file_size (filename, &filesize, GNUNET_YES, GNUNET_YES))
1177     filesize = 0;
1178   if (0 == filesize)
1179   {
1180     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Search strings file %s is empty.\n", filename);
1181     return GNUNET_SYSERR;
1182   }
1183   data = GNUNET_malloc (filesize);
1184   if (filesize != GNUNET_DISK_fn_read (filename, data, filesize))
1185   {
1186     GNUNET_free (data);
1187     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Could not read search strings file %s.\n",
1188          filename);
1189     return GNUNET_SYSERR;
1190   }
1191   buf = data;
1192   offset = 0;
1193   str_cnt = 0;
1194   while (offset < (filesize - 1) && str_cnt < limit)
1195   {
1196     offset++;
1197     if (((data[offset] == '\n')) && (buf != &data[offset]))
1198     {
1199       data[offset] = '\0';
1200       str_cnt++;
1201       buf = &data[offset + 1];
1202     }
1203     else if ((data[offset] == '\n') || (data[offset] == '\0'))
1204       buf = &data[offset + 1];
1205   }
1206   *strings = GNUNET_malloc (sizeof (char *) * str_cnt);
1207   offset = 0;
1208   for (i = 0; i < str_cnt; i++)
1209   {
1210     GNUNET_asprintf (&(*strings)[i], "%s%s", regex_prefix, &data[offset]);
1211     offset += strlen (&data[offset]) + 1;
1212   }
1213   GNUNET_free (data);
1214   return str_cnt;
1215 }
1216
1217
1218 /**
1219  * Main function that will be run by the scheduler.
1220  *
1221  * @param cls closure
1222  * @param args remaining command-line arguments
1223  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
1224  * @param config configuration
1225  */
1226 static void
1227 run (void *cls, char *const *args, const char *cfgfile,
1228      const struct GNUNET_CONFIGURATION_Handle *config)
1229 {
1230   unsigned int nsearchstrs;
1231   unsigned int i;
1232   char *hosts_file;
1233   char *strings_file;
1234
1235   /* Check config */
1236   if (NULL == config)
1237   {
1238     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1239                 _("No configuration file given. Exiting\n"));
1240     shutdown_task = GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1241     return;
1242   }
1243   cfg = GNUNET_CONFIGURATION_dup (config);
1244   if (GNUNET_OK !=
1245       GNUNET_CONFIGURATION_get_value_string (cfg, "REGEXPROFILER",
1246                                              "REGEX_PREFIX",
1247                                              &regex_prefix))
1248   {
1249     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1250                 _("Configuration option \"regex_prefix\" missing. Exiting\n"));
1251     shutdown_task = GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1252     return;
1253   }
1254   if (GNUNET_OK !=
1255       GNUNET_CONFIGURATION_get_value_time (cfg, "REGEXPROFILER",
1256                                            "REANNOUNCE_PERIOD_MAX",
1257                                            &reannounce_period_max))
1258   {
1259     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, 
1260                 "reannounce_period_max not given. Using 10 minutes.\n");
1261     reannounce_period_max =
1262       GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 10);
1263   }
1264
1265   /* Check arguments */
1266   hosts_file = args[0];
1267   if (NULL == hosts_file)
1268   {
1269     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1270                 _("No hosts-file specified on command line. Exiting.\n"));
1271     return;
1272   }
1273   policy_dir = args[1];
1274   if (NULL == policy_dir)
1275   {
1276     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1277                 _("No policy directory specified on command line. Exiting.\n"));
1278     return;
1279   }
1280   if (GNUNET_YES != GNUNET_DISK_directory_test (policy_dir, GNUNET_YES))
1281   {
1282     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1283                 _("Specified policies directory does not exist. Exiting.\n"));
1284     shutdown_task = GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1285     return;
1286   }
1287   if (-1 == (num_peers = GNUNET_DISK_directory_scan (policy_dir, NULL, NULL)))
1288   {
1289     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1290                 _("No files found in `%s'\n"),
1291                 policy_dir);
1292     return;
1293   }
1294   strings_file = args[2];
1295   if (GNUNET_YES != GNUNET_DISK_file_test (strings_file))
1296   {
1297     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1298                 _("No search strings file given. Exiting.\n"));
1299     shutdown_task = GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1300     return;
1301   }
1302   nsearchstrs = load_search_strings (strings_file,
1303                                      &search_strings,
1304                                      num_search_strings);
1305   if (num_search_strings != nsearchstrs)
1306   {
1307     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1308                 _("Error loading search strings."
1309                   "Given file does not contain enough strings. Exiting.\n"));
1310     shutdown_task = GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1311     return;
1312   }
1313   if (0 >= num_search_strings || NULL == search_strings)
1314   {
1315     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1316                 _("Error loading search strings. Exiting.\n"));
1317     shutdown_task = GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1318     return;
1319   }
1320   for (i = 0; i < num_search_strings; i++)
1321     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1322                 "search string: %s\n",
1323                 search_strings[i]);
1324
1325   /* Check logfile */
1326   if ( (NULL != data_filename) &&
1327        (NULL == (data_file =
1328                  GNUNET_DISK_file_open (data_filename,
1329                                         GNUNET_DISK_OPEN_READWRITE |
1330                                         GNUNET_DISK_OPEN_TRUNCATE |
1331                                         GNUNET_DISK_OPEN_CREATE,
1332                                         GNUNET_DISK_PERM_USER_READ |
1333                                         GNUNET_DISK_PERM_USER_WRITE))) )
1334   {
1335     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
1336                               "open",
1337                               data_filename);
1338     return;
1339   }
1340
1341   /* Initialize peers */
1342   peers = GNUNET_malloc (sizeof (struct RegexPeer) * num_peers);
1343   for (i = 0; i < num_peers; i++)
1344   {
1345     struct RegexPeer *peer = &peers[i];
1346     peer->id = i;
1347     peer->policy_file = NULL;
1348     peer->dht_handle = NULL;
1349     peer->search_handle = NULL;
1350     peer->stats_handle = NULL;
1351     peer->stats_op_handle = NULL;
1352     peer->search_str = NULL;
1353     peer->search_str_matched = GNUNET_NO;
1354   }
1355
1356   event_mask = 0LL;
1357 /* For feedback about the start process activate these and pass master_cb
1358   event_mask |= (1LL << GNUNET_TESTBED_ET_PEER_START);
1359   event_mask |= (1LL << GNUNET_TESTBED_ET_PEER_STOP);
1360   event_mask |= (1LL << GNUNET_TESTBED_ET_CONNECT);
1361   event_mask |= (1LL << GNUNET_TESTBED_ET_DISCONNECT);*/
1362   prof_start_time = GNUNET_TIME_absolute_get ();
1363   GNUNET_TESTBED_run (args[0],
1364                       cfg,
1365                       num_peers,
1366                       event_mask,
1367                       NULL,     /* master_controller_cb, */
1368                       NULL,     /* master_controller_cb cls */
1369                       &test_master,
1370                       NULL);    /* test_master cls */
1371   abort_task =
1372       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
1373                                     (GNUNET_TIME_UNIT_MINUTES, 5),
1374                                     &do_abort,
1375                                     (void*) __LINE__);
1376 }
1377
1378
1379 /**
1380  * Main function.
1381  *
1382  * @param argc argument count
1383  * @param argv argument values
1384  * @return 0 on success
1385  */
1386 int
1387 main (int argc, char *const *argv)
1388 {
1389   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
1390     {'d', "details", "FILENAME",
1391      gettext_noop ("name of the file for writing statistics"),
1392      1, &GNUNET_GETOPT_set_string, &data_filename},
1393     {'n', "num-links", "COUNT",
1394       gettext_noop ("create COUNT number of random links between peers"),
1395       GNUNET_YES, &GNUNET_GETOPT_set_uint, &linking_factor },
1396     {'t', "matching-timeout", "TIMEOUT",
1397       gettext_noop ("wait TIMEOUT before considering a string match as failed"),
1398       GNUNET_YES, &GNUNET_GETOPT_set_relative_time, &search_timeout_time
1399         },
1400     {'s', "search-delay", "DELAY",
1401       gettext_noop ("wait DELAY before starting string search"),
1402       GNUNET_YES, &GNUNET_GETOPT_set_relative_time, &search_delay },
1403     {'a', "num-search-strings", "COUNT",
1404       gettext_noop ("number of search strings to read from search strings file"),
1405       GNUNET_YES, &GNUNET_GETOPT_set_uint, &num_search_strings },
1406     {'p', "max-path-compression", "MAX_PATH_COMPRESSION",
1407      gettext_noop ("maximum path compression length"),
1408      1, &GNUNET_GETOPT_set_uint, &max_path_compression},
1409     GNUNET_GETOPT_OPTION_END
1410   };
1411   int ret;
1412
1413   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
1414     return 2;
1415
1416   result = GNUNET_SYSERR;
1417   ret =
1418       GNUNET_PROGRAM_run (argc, argv,
1419                           "gnunet-regex-profiler [OPTIONS] hosts-file policy-dir search-strings-file",
1420                           _("Profiler for regex"),
1421                           options, &run, NULL);
1422
1423   if (GNUNET_OK != ret)
1424     return ret;
1425   if (GNUNET_OK != result)
1426     return 1;
1427   return 0;
1428 }