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