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