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