a533f04c9f87c24e26459624dd27ff12fdd8fdde
[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
42 /**
43  * DLL of operations
44  */
45 struct DLLOperation
46 {
47   /**
48    * The testbed operation handle
49    */
50   struct GNUNET_TESTBED_Operation *op;
51
52   /**
53    * Closure
54    */
55   void *cls;
56
57   /**
58    * The next pointer for DLL
59    */
60   struct DLLOperation *next;
61
62   /**
63    * The prev pointer for DLL
64    */
65   struct DLLOperation *prev;
66 };
67
68
69 /**
70  * Available states during profiling
71  */
72 enum State
73 {
74   /**
75    * Initial state
76    */
77   STATE_INIT = 0,
78
79   /**
80    * Starting slaves
81    */
82   STATE_SLAVES_STARTING,
83
84   /**
85    * Creating peers
86    */
87   STATE_PEERS_CREATING,
88
89   /**
90    * Starting peers
91    */
92   STATE_PEERS_STARTING,
93
94   /**
95    * Linking peers
96    */
97   STATE_PEERS_LINKING,
98
99   /**
100    * Matching strings against announced regexes
101    */
102   STATE_SEARCH_REGEX,
103
104   /**
105    * Destroying peers; we can do this as the controller takes care of stopping a
106    * peer if it is running
107    */
108   STATE_PEERS_DESTROYING
109 };
110
111
112 /**
113  * Peer handles.
114  */
115 struct RegexPeer
116 {
117   /**
118    * Peer id.
119    */
120   unsigned int id;
121
122   /**
123    * Peer configuration handle.
124    */
125   struct GNUNET_CONFIGURATION_Handle *cfg;
126
127   /**
128    * The actual testbed peer handle.
129    */
130   struct GNUNET_TESTBED_Peer *peer_handle;
131
132   /**
133    * Peer's search string.
134    */
135   const char *search_str;
136
137   /**
138    * Set to GNUNET_YES if the peer successfully matched the above
139    * search string. GNUNET_NO if the string could not be matched
140    * during the profiler run. GNUNET_SYSERR if the string matching
141    * timed out. Undefined if search_str is NULL
142    */
143   int search_str_matched;
144
145   /**
146    * Peer's DHT handle.
147    */
148   struct GNUNET_DHT_Handle *dht_handle;
149
150   /**
151    * Handle to a running regex search.
152    */
153    struct GNUNET_REGEX_search_handle *search_handle;
154
155   /**
156    * Testbed operation handle for DHT.
157    */
158   struct GNUNET_TESTBED_Operation *op_handle;
159
160   /**
161    * Peers's statistics handle.
162    */
163   struct GNUNET_STATISTICS_Handle *stats_handle;
164
165   /**
166    * Testbed operation handle for the statistics service.
167    */
168   struct GNUNET_TESTBED_Operation *stats_op_handle;
169
170   /**
171    * The starting time of a profiling step.
172    */
173   struct GNUNET_TIME_Absolute prof_start_time;
174
175   /**
176    * Operation timeout
177    */
178   GNUNET_SCHEDULER_TaskIdentifier timeout;
179
180   /**
181    * Deamon start
182    */
183   struct GNUNET_TESTBED_Operation *daemon_op;
184 };
185
186 /**
187  * Set when shutting down to avoid making more queries.
188  */
189 static int in_shutdown;
190
191 /**
192  * The array of peers; we fill this as the peers are given to us by the testbed
193  */
194 static struct RegexPeer *peers;
195
196 /**
197  * Host registration handle
198  */
199 static struct GNUNET_TESTBED_HostRegistrationHandle *reg_handle;
200
201 /**
202  * Handle to the master controller process
203  */
204 static struct GNUNET_TESTBED_ControllerProc *mc_proc;
205
206 /**
207  * Handle to the master controller
208  */
209 static struct GNUNET_TESTBED_Controller *mc;
210
211 /**
212  * Handle to global configuration
213  */
214 static struct GNUNET_CONFIGURATION_Handle *cfg;
215
216 /**
217  * Abort task identifier
218  */
219 static GNUNET_SCHEDULER_TaskIdentifier abort_task;
220
221 /**
222  * Shutdown task identifier
223  */
224 static GNUNET_SCHEDULER_TaskIdentifier shutdown_task;
225
226 /**
227  * Host registration task identifier
228  */
229 static GNUNET_SCHEDULER_TaskIdentifier register_hosts_task;
230
231 /**
232  * Global event mask for all testbed events
233  */
234 static uint64_t event_mask;
235
236 /**
237  * The starting time of a profiling step
238  */
239 static struct GNUNET_TIME_Absolute prof_start_time;
240
241 /**
242  * Duration profiling step has taken
243  */
244 static struct GNUNET_TIME_Relative prof_time;
245
246 /**
247  * Number of peers to be started by the profiler
248  */
249 static unsigned int num_peers;
250
251 /**
252  * Global testing status
253  */
254 static int result;
255
256 /**
257  * current state of profiling
258  */
259 enum State state;
260
261 /**
262  * Folder where policy files are stored.
263  */
264 static char * policy_dir;
265
266 /**
267  * File with hostnames where to execute the test.
268  */
269 static char *hosts_file;
270
271 /**
272  * File with the strings to look for.
273  */
274 static char *strings_file;
275
276 /**
277  * Search strings.
278  */
279 static char **search_strings;
280
281 /**
282  * Number of search strings.
283  */
284 static int num_search_strings;
285
286 /**
287  * How many searches are we going to start in parallel
288  */
289 static long long unsigned int init_parallel_searches;
290
291 /**
292  * How many searches are running in parallel
293  */
294 static unsigned int parallel_searches;
295
296 /**
297  * Number of strings found in the published regexes.
298  */
299 static unsigned int strings_found;
300
301 /**
302  * Index of peer to start next announce/search.
303  */
304 static unsigned int next_search;
305
306 /**
307  * Search timeout task identifier.
308  */
309 static GNUNET_SCHEDULER_TaskIdentifier search_timeout_task;
310
311 /**
312  * Search timeout in seconds.
313  */
314 static struct GNUNET_TIME_Relative search_timeout_time = { 60000 };
315
316 /**
317  * File to log statistics to.
318  */
319 static struct GNUNET_DISK_FileHandle *data_file;
320
321 /**
322  * Filename to log statistics to.
323  */
324 static char *data_filename;
325
326 /**
327  * Prefix used for regex announcing. We need to prefix the search
328  * strings with it, in order to find something.
329  */
330 static char * regex_prefix;
331
332 /**
333  * What's the maximum regex reannounce period.
334  */
335 static struct GNUNET_TIME_Relative reannounce_period_max;
336
337
338 /******************************************************************************/
339 /******************************  DECLARATIONS  ********************************/
340 /******************************************************************************/
341
342 /**
343  * DHT connect callback.
344  *
345  * @param cls internal peer id.
346  * @param op operation handle.
347  * @param ca_result connect adapter result.
348  * @param emsg error message.
349  */
350 static void
351 dht_connect_cb (void *cls, struct GNUNET_TESTBED_Operation *op,
352                 void *ca_result, const char *emsg);
353
354 /**
355  * DHT connect adapter.
356  *
357  * @param cls not used.
358  * @param cfg configuration handle.
359  *
360  * @return
361  */
362 static void *
363 dht_ca (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg);
364
365
366 /**
367  * Adapter function called to destroy a connection to
368  * the DHT service
369  *
370  * @param cls closure
371  * @param op_result service handle returned from the connect adapter
372  */
373 static void
374 dht_da (void *cls, void *op_result);
375
376
377 /**
378  * Function called by testbed once we are connected to stats
379  * service. Get the statistics for the services of interest.
380  *
381  * @param cls the 'struct RegexPeer' for which we connected to stats
382  * @param op connect operation handle
383  * @param ca_result handle to stats service
384  * @param emsg error message on failure
385  */
386 static void
387 stats_connect_cb (void *cls,
388                   struct GNUNET_TESTBED_Operation *op,
389                   void *ca_result,
390                   const char *emsg);
391
392
393 /**
394  * Task to collect all statistics from s, will shutdown the
395  * profiler, when done.
396  *
397  * @param cls NULL
398  * @param tc the task context
399  */
400 static void
401 do_collect_stats (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
402
403
404 /**
405  * Start announcing the next regex in the DHT.
406  *
407  * @param cls Index of the next peer in the peers array.
408  * @param tc TaskContext.
409  */
410 static void
411 announce_next_regex (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
412
413
414 /******************************************************************************/
415 /********************************  SHUTDOWN  **********************************/
416 /******************************************************************************/
417
418
419 /**
420  * Shutdown nicely
421  *
422  * @param cls NULL
423  * @param tc the task context
424  */
425 static void
426 do_shutdown (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
427 {
428   struct RegexPeer *peer;
429   unsigned int peer_cnt;
430   unsigned int search_str_cnt;
431   char output_buffer[512];
432   size_t size;
433
434   shutdown_task = GNUNET_SCHEDULER_NO_TASK;
435   if (GNUNET_SCHEDULER_NO_TASK != abort_task)
436     GNUNET_SCHEDULER_cancel (abort_task);
437   if (GNUNET_SCHEDULER_NO_TASK != register_hosts_task)
438     GNUNET_SCHEDULER_cancel (register_hosts_task);
439
440   for (peer_cnt = 0; peer_cnt < num_peers; peer_cnt++)
441   {
442     peer = &peers[peer_cnt];
443
444     if (GNUNET_YES != peer->search_str_matched && NULL != data_file)
445     {
446       prof_time = GNUNET_TIME_absolute_get_duration (peer->prof_start_time);
447       size =
448         GNUNET_snprintf (output_buffer,
449                          sizeof (output_buffer),
450                          "%p Search string not found: %s (%d)\n"
451                          "%p On peer: %u (%p)\n"
452                          "%p After: %s\n",
453                          peer, peer->search_str, peer->search_str_matched,
454                          peer, peer->id, peer,
455                          peer,
456                          GNUNET_STRINGS_relative_time_to_string (prof_time,
457                                                                  GNUNET_NO));
458       if (size != GNUNET_DISK_file_write (data_file, output_buffer, size))
459         GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Unable to write to file!\n");
460     }
461
462     if (NULL != peers[peer_cnt].op_handle)
463       GNUNET_TESTBED_operation_done (peers[peer_cnt].op_handle);
464     if (NULL != peers[peer_cnt].stats_op_handle)
465       GNUNET_TESTBED_operation_done (peers[peer_cnt].stats_op_handle);
466   }
467
468   if (NULL != data_file)
469     GNUNET_DISK_file_close (data_file);
470
471   for (search_str_cnt = 0;
472        search_str_cnt < num_search_strings && NULL != search_strings;
473        search_str_cnt++)
474   {
475     GNUNET_free_non_null (search_strings[search_str_cnt]);
476   }
477   GNUNET_free_non_null (search_strings);
478
479   if (NULL != reg_handle)
480     GNUNET_TESTBED_cancel_registration (reg_handle);
481
482   if (NULL != mc)
483     GNUNET_TESTBED_controller_disconnect (mc);
484   if (NULL != mc_proc)
485     GNUNET_TESTBED_controller_stop (mc_proc);
486   if (NULL != cfg)
487     GNUNET_CONFIGURATION_destroy (cfg);
488
489   GNUNET_SCHEDULER_shutdown (); /* Stop scheduler to shutdown testbed run */
490 }
491
492
493 /**
494  * abort task to run on test timed out
495  *
496  * @param cls NULL
497  * @param tc the task context
498  */
499 static void
500 do_abort (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
501 {
502   unsigned long i = (unsigned long) cls;
503
504   GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Aborting from line %lu...\n", i);
505   abort_task = GNUNET_SCHEDULER_NO_TASK;
506   result = GNUNET_SYSERR;
507   if (GNUNET_SCHEDULER_NO_TASK != shutdown_task)
508     GNUNET_SCHEDULER_cancel (shutdown_task);
509   shutdown_task = GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
510 }
511
512
513 /******************************************************************************/
514 /*********************  STATISTICS SERVICE CONNECTIONS  ***********************/
515 /******************************************************************************/
516
517 /**
518  * Adapter function called to establish a connection to
519  * statistics service.
520  *
521  * @param cls closure
522  * @param cfg configuration of the peer to connect to; will be available until
523  *          GNUNET_TESTBED_operation_done() is called on the operation returned
524  *          from GNUNET_TESTBED_service_connect()
525  * @return service handle to return in 'op_result', NULL on error
526  */
527 static void *
528 stats_ca (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg)
529 {
530   return GNUNET_STATISTICS_create ("<driver>", cfg);
531 }
532
533
534 /**
535  * Adapter function called to destroy a connection to
536  * statistics service.
537  *
538  * @param cls closure
539  * @param op_result service handle returned from the connect adapter
540  */
541 static void
542 stats_da (void *cls, void *op_result)
543 {
544   struct RegexPeer *peer = cls;
545
546   GNUNET_assert (op_result == peer->stats_handle);
547
548   GNUNET_STATISTICS_destroy (peer->stats_handle, GNUNET_NO);
549   peer->stats_handle = NULL;
550 }
551
552
553 /**
554  * Process statistic values. Write all values to global 'data_file', if present.
555  *
556  * @param cls closure
557  * @param subsystem name of subsystem that created the statistic
558  * @param name the name of the datum
559  * @param value the current value
560  * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
561  * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
562  */
563 static int
564 stats_iterator (void *cls, const char *subsystem, const char *name,
565                 uint64_t value, int is_persistent)
566 {
567   struct RegexPeer *peer = cls;
568   char output_buffer[512];
569   size_t size;
570
571   if (NULL == data_file)
572   {
573     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
574                 "%p -> %s [%s]: %llu\n",
575                 peer, subsystem, name, value);
576     return GNUNET_OK;
577   }
578   size =
579     GNUNET_snprintf (output_buffer,
580                      sizeof (output_buffer),
581                      "%p [%s] %llu %s\n",
582                      peer,
583                      subsystem, value, name);
584   if (size != GNUNET_DISK_file_write (data_file, output_buffer, size))
585     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Unable to write to file!\n");
586
587   return GNUNET_OK;
588 }
589
590
591 /**
592  * Stats callback. Finish the stats testbed operation and when all stats have
593  * been iterated, shutdown the profiler.
594  *
595  * @param cls closure
596  * @param success GNUNET_OK if statistics were
597  *        successfully obtained, GNUNET_SYSERR if not.
598  */
599 static void
600 stats_cb (void *cls,
601           int success)
602 {
603   static unsigned int peer_cnt;
604   struct RegexPeer *peer = cls;
605
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   if (GNUNET_YES == peer->search_str_matched)
747   {
748     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
749                 "String %s on peer %u already matched!\n",
750                 peer->search_str, peer->id);
751     return;
752   }
753
754   strings_found++;
755   parallel_searches--;
756
757   if (GNUNET_SCHEDULER_NO_TASK != peer->timeout)
758   {
759     GNUNET_SCHEDULER_cancel (peer->timeout);
760     peer->timeout = GNUNET_SCHEDULER_NO_TASK;
761     if (GNUNET_NO == in_shutdown)
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, strings_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                 strings_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"
791                          "%p Search string: %s\n"
792                          "%p Search duration: %s\n\n",
793                          peer, peer->id,
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 (strings_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_timed_out (void *cls, const struct GNUNET_SCHEDULER_TaskContext * tc)
832 {
833   unsigned int i;
834
835   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
836               "Finding matches to all strings did not succeed after %s.\n",
837               GNUNET_STRINGS_relative_time_to_string (search_timeout_time,
838                                                       GNUNET_NO));
839   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
840               "Found %i of %i strings\n", strings_found, num_search_strings);
841
842   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
843               "Search timed out after %s."
844               "Collecting stats and shutting down.\n", 
845               GNUNET_STRINGS_relative_time_to_string (search_timeout_time,
846                                                       GNUNET_NO));
847
848   in_shutdown = GNUNET_YES;
849   for (i = 0; i < num_peers; i++)
850   {
851     if (NULL != peers[i].op_handle)
852     {
853       GNUNET_TESTBED_operation_done (peers[i].op_handle);
854       peers[i].op_handle = NULL;
855     }
856   }
857   GNUNET_SCHEDULER_add_now (&do_collect_stats, NULL);
858 }
859
860
861 /**
862  * Search timed out. It might still complete in the future,
863  * but we should start another one.
864  *
865  * @param cls Index of the next peer in the peers array.
866  * @param tc TaskContext.
867  */
868 static void
869 find_timed_out (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
870 {
871   struct RegexPeer *p = cls;
872
873   p->timeout = GNUNET_SCHEDULER_NO_TASK;
874
875   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
876     return;
877   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
878               "Searching for string \"%s\" on peer %d timed out."
879               "Starting new search: %d.\n",
880               p->search_str,
881               p->id,
882               !in_shutdown);
883   if (GNUNET_NO == in_shutdown)
884     GNUNET_SCHEDULER_add_now (&announce_next_regex, NULL);
885 }
886
887
888 /**
889  * Start searching for a string in the DHT.
890  *
891  * @param cls Index of the next peer in the peers array.
892  * @param tc TaskContext.
893  */
894 static void
895 find_string (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
896 {
897   unsigned int search_peer = (unsigned int) (long) cls;
898
899   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) ||
900       search_peer >= num_search_strings)
901     return;
902
903   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
904               "Searching for string \"%s\" on peer %d (%u||)\n",
905               peers[search_peer].search_str,
906               search_peer,
907               parallel_searches);
908
909   peers[search_peer].op_handle =
910     GNUNET_TESTBED_service_connect (NULL,
911                                     peers[search_peer].peer_handle,
912                                     "dht",
913                                     &dht_connect_cb,
914                                     &peers[search_peer],
915                                     &dht_ca,
916                                     &dht_da,
917                                     &peers[search_peer]);
918   GNUNET_assert (NULL != peers[search_peer].op_handle);
919   peers[search_peer].timeout = GNUNET_SCHEDULER_add_delayed (FIND_TIMEOUT,
920                                                           &find_timed_out,
921                                                           &peers[search_peer]);
922 }
923
924
925
926
927 /**
928  * Callback called when testbed has started the daemon we asked for.
929  *
930  * @param cls NULL
931  * @param op the operation handle
932  * @param emsg NULL on success; otherwise an error description
933  */
934 static void
935 daemon_started (void *cls, struct GNUNET_TESTBED_Operation *op,
936                 const char *emsg)
937 {
938   struct RegexPeer *peer = (struct RegexPeer *) cls;
939   unsigned long search_peer;
940   unsigned int i;
941   unsigned int me;
942
943   GNUNET_TESTBED_operation_done (peer->daemon_op);
944   peer->daemon_op = NULL;
945   me = peer - peers;
946   if (NULL != emsg)
947   {
948     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
949                 "Failed to start/stop daemon at peer %u: %s\n", me, emsg);
950     GNUNET_abort ();
951   }
952
953   /* Find a peer to look for a string matching the regex announced */
954   search_peer = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
955                                           num_peers);
956   for (i = 0; peers[search_peer].search_str != NULL; i++)
957   {
958     search_peer = (search_peer + 1) % num_peers;
959     if (i > num_peers)
960       GNUNET_abort (); /* we ran out of peers, must be a bug */
961   }
962   peers[search_peer].search_str = search_strings[me];
963   peers[search_peer].search_str_matched = GNUNET_NO;
964   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply(
965                                   reannounce_period_max,
966                                   2),
967                                 &find_string,
968                                 (void *) search_peer);
969 }
970
971
972 /**
973  * Task to start the daemons on each peer so that the regexes are announced
974  * into the DHT.
975  *
976  * @param cls NULL
977  * @param tc the task context
978  */
979 static void
980 do_announce (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
981 {
982   unsigned int i;
983
984   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Starting announce.\n");
985
986   for (i = 0; i < init_parallel_searches; i++)
987   {
988     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
989                 "  scheduling announce %u\n",
990                 i);
991     (void) GNUNET_SCHEDULER_add_now (&announce_next_regex, NULL);
992   }
993 }
994
995
996 /**
997  * Start announcing the next regex in the DHT.
998  *
999  * @param cls Closure (unused).
1000  * @param tc TaskContext.
1001  */
1002 static void
1003 announce_next_regex (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1004 {
1005   struct RegexPeer *peer;
1006
1007   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) ||
1008             next_search >= num_peers)
1009     return;
1010
1011   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Starting daemon %u\n", next_search);
1012   peer = &peers[next_search];
1013   peer->daemon_op = 
1014   GNUNET_TESTBED_peer_manage_service (NULL,
1015                                       peer->peer_handle,
1016                                       "regexprofiler",
1017                                       &daemon_started,
1018                                       peer,
1019                                       1);
1020   next_search++;
1021   parallel_searches++;
1022 }
1023
1024 /**
1025  * DHT connect callback. Called when we are connected to the dht service for
1026  * the peer in 'cls'. If successfull we connect to the stats service of this
1027  * peer and then try to match the search string of this peer.
1028  *
1029  * @param cls internal peer id.
1030  * @param op operation handle.
1031  * @param ca_result connect adapter result.
1032  * @param emsg error message.
1033  */
1034 static void
1035 dht_connect_cb (void *cls, struct GNUNET_TESTBED_Operation *op,
1036                 void *ca_result, const char *emsg)
1037 {
1038   struct RegexPeer *peer = (struct RegexPeer *) cls;
1039
1040   if (NULL != emsg || NULL == op || NULL == ca_result)
1041   {
1042     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "DHT connect failed: %s\n", emsg);
1043     GNUNET_abort ();
1044   }
1045
1046   GNUNET_assert (NULL != peer->dht_handle);
1047   GNUNET_assert (peer->op_handle == op);
1048   GNUNET_assert (peer->dht_handle == ca_result);
1049
1050   peer->search_str_matched = GNUNET_NO;
1051   peer->search_handle = GNUNET_REGEX_search (peer->dht_handle,
1052                                              peer->search_str,
1053                                              &regex_found_handler, peer,
1054                                              NULL);
1055   peer->prof_start_time = GNUNET_TIME_absolute_get ();
1056 }
1057
1058
1059 /**
1060  * DHT connect adapter. Opens a connection to the dht service.
1061  *
1062  * @param cls Closure (peer).
1063  * @param cfg Configuration handle.
1064  *
1065  * @return
1066  */
1067 static void *
1068 dht_ca (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg)
1069 {
1070   struct RegexPeer *peer = cls;
1071
1072   peer->dht_handle = GNUNET_DHT_connect (cfg, 32);
1073
1074   return peer->dht_handle;
1075 }
1076
1077
1078 /**
1079  * Adapter function called to destroy a connection to the dht service.
1080  *
1081  * @param cls Closure (peer).
1082  * @param op_result Service handle returned from the connect adapter.
1083  */
1084 static void
1085 dht_da (void *cls, void *op_result)
1086 {
1087   struct RegexPeer *peer = (struct RegexPeer *) cls;
1088
1089   GNUNET_assert (peer->dht_handle == op_result);
1090
1091   if (NULL != peer->search_handle)
1092   {
1093     GNUNET_REGEX_search_cancel (peer->search_handle);
1094     peer->search_handle = NULL;
1095   }
1096
1097   if (NULL != peer->dht_handle)
1098   {
1099     GNUNET_DHT_disconnect (peer->dht_handle);
1100     peer->dht_handle = NULL;
1101   }
1102 }
1103
1104
1105 /**
1106  * Signature of a main function for a testcase.
1107  *
1108  * @param cls NULL
1109  * @param num_peers_ number of peers in 'peers'
1110  * @param peers handle to peers run in the testbed.  NULL upon timeout (see
1111  *          GNUNET_TESTBED_test_run()).
1112  * @param links_succeeded the number of overlay link connection attempts that
1113  *          succeeded
1114  * @param links_failed the number of overlay link connection attempts that
1115  *          failed
1116  */
1117 static void 
1118 test_master (void *cls,
1119              unsigned int num_peers_,
1120              struct GNUNET_TESTBED_Peer **testbed_peers,
1121              unsigned int links_succeeded,
1122              unsigned int links_failed)
1123 {
1124   unsigned int i;
1125
1126   GNUNET_assert (num_peers_ == num_peers);
1127
1128   prof_time = GNUNET_TIME_absolute_get_duration (prof_start_time);
1129   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1130               "Testbed started in %s\n",
1131               GNUNET_STRINGS_relative_time_to_string (prof_time, GNUNET_NO));
1132
1133   if (GNUNET_SCHEDULER_NO_TASK != abort_task)
1134   {
1135     GNUNET_SCHEDULER_cancel (abort_task);
1136     abort_task = GNUNET_SCHEDULER_NO_TASK;
1137   }
1138
1139   for (i = 0; i < num_peers; i++)
1140   {
1141     peers[i].peer_handle = testbed_peers[i];
1142   }
1143   GNUNET_SCHEDULER_add_now (&do_announce, NULL);
1144   search_timeout_task =
1145       GNUNET_SCHEDULER_add_delayed (search_timeout_time, &search_timed_out, NULL);
1146 }
1147
1148 /**
1149  * Function that will be called whenever something in the testbed changes.
1150  *
1151  * @param cls closure, NULL
1152  * @param event information on what is happening
1153  */
1154 static void
1155 master_controller_cb (void *cls, 
1156                       const struct GNUNET_TESTBED_EventInformation *event)
1157 {
1158   switch (event->type)
1159   {
1160   case GNUNET_TESTBED_ET_CONNECT:
1161     printf(".");
1162     break;
1163   case GNUNET_TESTBED_ET_PEER_START:
1164     printf("#");
1165     break;
1166   default:
1167     break;
1168   }
1169   fflush(stdout);
1170 }
1171
1172
1173 /******************************************************************************/
1174 /***************************  TESTBED PEER SETUP  *****************************/
1175 /******************************************************************************/
1176
1177
1178 /**
1179  * Load search strings from given filename. One search string per line.
1180  *
1181  * @param filename filename of the file containing the search strings.
1182  * @param strings set of strings loaded from file. Caller needs to free this
1183  *                if number returned is greater than zero.
1184  * @param limit upper limit on the number of strings read from the file
1185  * @return number of strings found in the file. GNUNET_SYSERR on error.
1186  */
1187 static int
1188 load_search_strings (const char *filename, char ***strings, unsigned int limit)
1189 {
1190   char *data;
1191   char *buf;
1192   uint64_t filesize;
1193   unsigned int offset;
1194   int str_cnt;
1195   unsigned int i;
1196
1197   if (NULL == filename)
1198   {
1199     return GNUNET_SYSERR;
1200   }
1201
1202   if (GNUNET_YES != GNUNET_DISK_file_test (filename))
1203   {
1204     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1205                 "Could not find search strings file %s\n", filename);
1206     return GNUNET_SYSERR;
1207   }
1208   if (GNUNET_OK != GNUNET_DISK_file_size (filename, &filesize, GNUNET_YES, GNUNET_YES))
1209     filesize = 0;
1210   if (0 == filesize)
1211   {
1212     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Search strings file %s is empty.\n", filename);
1213     return GNUNET_SYSERR;
1214   }
1215   data = GNUNET_malloc (filesize);
1216   if (filesize != GNUNET_DISK_fn_read (filename, data, filesize))
1217   {
1218     GNUNET_free (data);
1219     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Could not read search strings file %s.\n",
1220          filename);
1221     return GNUNET_SYSERR;
1222   }
1223   buf = data;
1224   offset = 0;
1225   str_cnt = 0;
1226   while (offset < (filesize - 1) && str_cnt < limit)
1227   {
1228     offset++;
1229     if (((data[offset] == '\n')) && (buf != &data[offset]))
1230     {
1231       data[offset] = '\0';
1232       str_cnt++;
1233       buf = &data[offset + 1];
1234     }
1235     else if ((data[offset] == '\n') || (data[offset] == '\0'))
1236       buf = &data[offset + 1];
1237   }
1238   *strings = GNUNET_malloc (sizeof (char *) * str_cnt);
1239   offset = 0;
1240   for (i = 0; i < str_cnt; i++)
1241   {
1242     GNUNET_asprintf (&(*strings)[i], "%s%s", regex_prefix, &data[offset]);
1243     offset += strlen (&data[offset]) + 1;
1244   }
1245   GNUNET_free (data);
1246   return str_cnt;
1247 }
1248
1249
1250 /**
1251  * Main function that will be run by the scheduler.
1252  *
1253  * @param cls closure
1254  * @param args remaining command-line arguments
1255  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
1256  * @param config configuration
1257  */
1258 static void
1259 run (void *cls, char *const *args, const char *cfgfile,
1260      const struct GNUNET_CONFIGURATION_Handle *config)
1261 {
1262   unsigned int nsearchstrs;
1263   unsigned int i;
1264
1265   in_shutdown = GNUNET_NO;
1266
1267   /* Check config */
1268   if (NULL == config)
1269   {
1270     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1271                 _("No configuration file given. Exiting\n"));
1272     shutdown_task = GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1273     return;
1274   }
1275   cfg = GNUNET_CONFIGURATION_dup (config);
1276   if (GNUNET_OK !=
1277       GNUNET_CONFIGURATION_get_value_string (cfg, "REGEXPROFILER",
1278                                              "REGEX_PREFIX",
1279                                              &regex_prefix))
1280   {
1281     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1282                 _("Configuration option \"regex_prefix\" missing. Exiting\n"));
1283     shutdown_task = GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1284     return;
1285   }
1286   if (GNUNET_OK !=
1287       GNUNET_CONFIGURATION_get_value_number (cfg, "REGEXPROFILER",
1288                                              "PARALLEL_SEARCHES",
1289                                              &init_parallel_searches))
1290   {
1291     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1292                 "Configuration option \"PARALLEL_SEARCHES\" missing."
1293                 " Using default (%d)\n", 10);
1294     init_parallel_searches = 10;
1295   }
1296   if (GNUNET_OK !=
1297       GNUNET_CONFIGURATION_get_value_time (cfg, "REGEXPROFILER",
1298                                            "REANNOUNCE_PERIOD_MAX",
1299                                            &reannounce_period_max))
1300   {
1301     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, 
1302                 "reannounce_period_max not given. Using 10 minutes.\n");
1303     reannounce_period_max =
1304       GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 10);
1305   }
1306
1307   /* Check arguments */
1308   if (NULL == policy_dir)
1309   {
1310     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1311                 _("No policy directory specified on command line. Exiting.\n"));
1312     return;
1313   }
1314   if (GNUNET_YES != GNUNET_DISK_directory_test (policy_dir, GNUNET_YES))
1315   {
1316     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1317                 _("Specified policies directory does not exist. Exiting.\n"));
1318     shutdown_task = GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1319     return;
1320   }
1321   if (-1 == (num_peers = GNUNET_DISK_directory_scan (policy_dir, NULL, NULL)))
1322   {
1323     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1324                 _("No files found in `%s'\n"),
1325                 policy_dir);
1326     return;
1327   }
1328   GNUNET_CONFIGURATION_set_value_string (cfg, "REGEXPROFILER",
1329                                          "POLICY_DIR", policy_dir);
1330   if (GNUNET_YES != GNUNET_DISK_file_test (strings_file))
1331   {
1332     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1333                 _("No search strings file given. Exiting.\n"));
1334     shutdown_task = GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1335     return;
1336   }
1337   nsearchstrs = load_search_strings (strings_file,
1338                                      &search_strings,
1339                                      num_search_strings);
1340   if (num_search_strings != nsearchstrs)
1341   {
1342     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1343                 _("Error loading search strings."
1344                   "Given file does not contain enough strings. Exiting.\n"));
1345     shutdown_task = GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1346     return;
1347   }
1348   if (0 >= num_search_strings || NULL == search_strings)
1349   {
1350     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1351                 _("Error loading search strings. Exiting.\n"));
1352     shutdown_task = GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1353     return;
1354   }
1355   for (i = 0; i < num_search_strings; i++)
1356     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1357                 "search string: %s\n",
1358                 search_strings[i]);
1359
1360   /* Check logfile */
1361   if ( (NULL != data_filename) &&
1362        (NULL == (data_file =
1363                  GNUNET_DISK_file_open (data_filename,
1364                                         GNUNET_DISK_OPEN_READWRITE |
1365                                         GNUNET_DISK_OPEN_TRUNCATE |
1366                                         GNUNET_DISK_OPEN_CREATE,
1367                                         GNUNET_DISK_PERM_USER_READ |
1368                                         GNUNET_DISK_PERM_USER_WRITE))) )
1369   {
1370     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
1371                               "open",
1372                               data_filename);
1373     return;
1374   }
1375
1376   /* Initialize peers */
1377   peers = GNUNET_malloc (sizeof (struct RegexPeer) * num_peers);
1378   for (i = 0; i < num_peers; i++)
1379   {
1380     peers[i].id = i;
1381   }
1382
1383   event_mask = 0LL;
1384 /* For feedback about the start process activate these and pass master_cb */
1385   event_mask |= (1LL << GNUNET_TESTBED_ET_PEER_START);
1386 //   event_mask |= (1LL << GNUNET_TESTBED_ET_PEER_STOP);
1387   event_mask |= (1LL << GNUNET_TESTBED_ET_CONNECT);
1388 //   event_mask |= (1LL << GNUNET_TESTBED_ET_DISCONNECT);
1389   prof_start_time = GNUNET_TIME_absolute_get ();
1390   GNUNET_TESTBED_run (hosts_file,
1391                       cfg,
1392                       num_peers,
1393                       event_mask,
1394                       &master_controller_cb,
1395                       NULL,     /* master_controller_cb cls */
1396                       &test_master,
1397                       NULL);    /* test_master cls */
1398   abort_task =
1399       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
1400                                     (GNUNET_TIME_UNIT_MINUTES, 15),
1401                                     &do_abort,
1402                                     (void*) __LINE__);
1403 }
1404
1405
1406 /**
1407  * Main function.
1408  *
1409  * @param argc argument count
1410  * @param argv argument values
1411  * @return 0 on success
1412  */
1413 int
1414 main (int argc, char *const *argv)
1415 {
1416   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
1417     {'o', "output-file", "FILENAME",
1418      gettext_noop ("name of the file for writing statistics"),
1419      GNUNET_YES, &GNUNET_GETOPT_set_string, &data_filename},
1420     {'t', "matching-timeout", "TIMEOUT",
1421       gettext_noop ("wait TIMEOUT before ending the experiment"),
1422       GNUNET_YES, &GNUNET_GETOPT_set_relative_time, &search_timeout_time },
1423     {'n', "num-search-strings", "COUNT",
1424       gettext_noop ("number of search strings to read from search strings file"),
1425       GNUNET_YES, &GNUNET_GETOPT_set_uint, &num_search_strings },
1426     {'p', "policy-dir", "DIRECTORY",
1427       gettext_noop ("directory with policy files"),
1428       GNUNET_YES, &GNUNET_GETOPT_set_filename, &policy_dir },
1429     {'s', "strings-file", "FILENAME",
1430       gettext_noop ("name of file with input strings"),
1431       GNUNET_YES, &GNUNET_GETOPT_set_filename, &strings_file },
1432     {'H', "hosts-file", "FILENAME",
1433       gettext_noop ("name of file with hosts' names"),
1434       GNUNET_NO, &GNUNET_GETOPT_set_filename, &hosts_file },
1435     GNUNET_GETOPT_OPTION_END
1436   };
1437   int ret;
1438
1439   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
1440     return 2;
1441   result = GNUNET_SYSERR;
1442   ret =
1443       GNUNET_PROGRAM_run (argc, argv,
1444                           "gnunet-regex-profiler",
1445                           _("Profiler for regex"),
1446                           options, &run, NULL);
1447   if (GNUNET_OK != ret)
1448     return ret;
1449   if (GNUNET_OK != result)
1450     return 1;
1451   return 0;
1452 }