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