fixing compiler warnings
[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                                      GNUNET_TIME_UNIT_FOREVER_REL,
667                                      &stats_cb,
668                                      &stats_iterator, peer))
669   {
670     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
671                 "Could not get statistics of peer %u!\n", peer->id);
672   }
673 }
674
675
676 /**
677  * Task to collect all statistics from all peers, will shutdown the
678  * profiler, when done.
679  *
680  * @param cls NULL
681  */
682 static void
683 do_collect_stats (void *cls)
684 {
685   struct RegexPeer *peer = &peers[0];
686
687   GNUNET_assert (NULL != peer->peer_handle);
688
689   peer->op_handle =
690     GNUNET_TESTBED_service_connect (NULL,
691                                     peer->peer_handle,
692                                     "statistics",
693                                     &stats_connect_cb,
694                                     peer,
695                                     &stats_ca,
696                                     &stats_da,
697                                     peer);
698 }
699
700
701 /******************************************************************************/
702 /************************   REGEX FIND CONNECTIONS   **************************/
703 /******************************************************************************/
704
705
706 /**
707  * Start searching for the next string in the DHT.
708  *
709  * @param cls Index of the next peer in the peers array.
710  */
711 static void
712 find_string (void *cls);
713
714
715 /**
716  * Method called when we've found a peer that announced a regex
717  * that matches our search string. Now get the statistics.
718  *
719  * @param cls Closure provided in REGEX_INTERNAL_search.
720  * @param id Peer providing a regex that matches the string.
721  * @param get_path Path of the get request.
722  * @param get_path_length Lenght of get_path.
723  * @param put_path Path of the put request.
724  * @param put_path_length Length of the put_path.
725  */
726 static void
727 regex_found_handler (void *cls,
728                      const struct GNUNET_PeerIdentity *id,
729                      const struct GNUNET_PeerIdentity *get_path,
730                      unsigned int get_path_length,
731                      const struct GNUNET_PeerIdentity *put_path,
732                      unsigned int put_path_length)
733 {
734   struct RegexPeer *peer = cls;
735   char output_buffer[512];
736   size_t size;
737
738   if (GNUNET_YES == peer->search_str_matched)
739   {
740     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
741                 "String %s on peer %u already matched!\n",
742                 peer->search_str, peer->id);
743     return;
744   }
745
746   strings_found++;
747   parallel_searches--;
748
749   if (NULL != peer->timeout)
750   {
751     GNUNET_SCHEDULER_cancel (peer->timeout);
752     peer->timeout = NULL;
753     if (GNUNET_NO == in_shutdown)
754       GNUNET_SCHEDULER_add_now (&announce_next_regex, NULL);
755   }
756
757   if (NULL == id)
758   {
759     // FIXME not possible right now
760     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
761                 "String matching timed out for string %s on peer %u (%i/%i)\n",
762                 peer->search_str, peer->id, strings_found, num_peers);
763     peer->search_str_matched = GNUNET_SYSERR;
764   }
765   else
766   {
767     prof_time = GNUNET_TIME_absolute_get_duration (peer->prof_start_time);
768
769     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
770                 "String %s found on peer %u after %s (%i/%i) (%u||)\n",
771                 peer->search_str, peer->id,
772                 GNUNET_STRINGS_relative_time_to_string (prof_time, GNUNET_NO),
773                 strings_found, num_peers, parallel_searches);
774
775     peer->search_str_matched = GNUNET_YES;
776
777     if (NULL != data_file)
778     {
779       size =
780         GNUNET_snprintf (output_buffer,
781                          sizeof (output_buffer),
782                          "%p Peer: %u\n"
783                          "%p Search string: %s\n"
784                          "%p Search duration: %s\n\n",
785                          peer, peer->id,
786                          peer, peer->search_str,
787                          peer,
788                          GNUNET_STRINGS_relative_time_to_string (prof_time,
789                                                                  GNUNET_NO));
790
791       if (size != GNUNET_DISK_file_write (data_file, output_buffer, size))
792         GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Unable to write to file!\n");
793     }
794   }
795
796   GNUNET_TESTBED_operation_done (peer->op_handle);
797   peer->op_handle = NULL;
798
799   if (strings_found == num_peers)
800   {
801     prof_time = GNUNET_TIME_absolute_get_duration (prof_start_time);
802     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
803                 "All strings successfully matched in %s\n",
804                 GNUNET_STRINGS_relative_time_to_string (prof_time, GNUNET_NO));
805
806     if (NULL != search_timeout_task)
807     {
808       GNUNET_SCHEDULER_cancel (search_timeout_task);
809       search_timeout_task = NULL;
810     }
811
812     GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Collecting stats.\n");
813     GNUNET_SCHEDULER_add_now (&do_collect_stats, NULL);
814   }
815 }
816
817
818 /**
819  * Connect by string timeout task. This will cancel the profiler after the
820  * specified timeout 'search_timeout'.
821  *
822  * @param cls NULL
823  */
824 static void
825 search_timed_out (void *cls)
826 {
827   unsigned int i;
828
829   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
830               "Finding matches to all strings did not succeed after %s.\n",
831               GNUNET_STRINGS_relative_time_to_string (search_timeout_time,
832                                                       GNUNET_NO));
833   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
834               "Found %i of %i strings\n", strings_found, num_peers);
835
836   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
837               "Search timed out after %s."
838               "Collecting stats and shutting down.\n",
839               GNUNET_STRINGS_relative_time_to_string (search_timeout_time,
840                                                       GNUNET_NO));
841
842   in_shutdown = GNUNET_YES;
843   for (i = 0; i < num_peers; i++)
844   {
845     if (NULL != peers[i].op_handle)
846     {
847       GNUNET_TESTBED_operation_done (peers[i].op_handle);
848       peers[i].op_handle = NULL;
849     }
850   }
851   GNUNET_SCHEDULER_add_now (&do_collect_stats, NULL);
852 }
853
854
855 /**
856  * Search timed out. It might still complete in the future,
857  * but we should start another one.
858  *
859  * @param cls Index of the next peer in the peers array.
860  */
861 static void
862 find_timed_out (void *cls)
863 {
864   struct RegexPeer *p = cls;
865
866   p->timeout = NULL;
867   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
868               "Searching for string \"%s\" on peer %d timed out.\n",
869               p->search_str,
870               p->id);
871   if (GNUNET_NO == in_shutdown)
872     GNUNET_SCHEDULER_add_now (&announce_next_regex, NULL);
873 }
874
875
876 /**
877  * Start searching for a string in the DHT.
878  *
879  * @param cls Index of the next peer in the peers array.
880  */
881 static void
882 find_string (void *cls)
883 {
884   unsigned int search_peer = (unsigned int) (long) cls;
885
886   if ( (search_peer >= num_peers) ||
887        (GNUNET_YES == in_shutdown) )
888     return;
889
890   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
891               "Searching for string \"%s\" on peer %d (%u||)\n",
892               peers[search_peer].search_str,
893               search_peer,
894               parallel_searches);
895
896   peers[search_peer].op_handle =
897     GNUNET_TESTBED_service_connect (NULL,
898                                     peers[search_peer].peer_handle,
899                                     "dht",
900                                     &dht_connect_cb,
901                                     &peers[search_peer],
902                                     &dht_ca,
903                                     &dht_da,
904                                     &peers[search_peer]);
905   GNUNET_assert (NULL != peers[search_peer].op_handle);
906   peers[search_peer].timeout
907     = GNUNET_SCHEDULER_add_delayed (FIND_TIMEOUT,
908                                     &find_timed_out,
909                                     &peers[search_peer]);
910 }
911
912
913 /**
914  * Callback called when testbed has started the daemon we asked for.
915  *
916  * @param cls NULL
917  * @param op the operation handle
918  * @param emsg NULL on success; otherwise an error description
919  */
920 static void
921 daemon_started (void *cls,
922                 struct GNUNET_TESTBED_Operation *op,
923                 const char *emsg)
924 {
925   struct RegexPeer *peer = (struct RegexPeer *) cls;
926   unsigned long search_peer;
927   unsigned int i;
928
929   GNUNET_TESTBED_operation_done (peer->daemon_op);
930   peer->daemon_op = NULL;
931   if (NULL != emsg)
932   {
933     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
934                 "Failed to start/stop daemon at peer %u: %s\n", peer->id, emsg);
935     GNUNET_assert (0);
936   }
937   else
938   {
939     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
940                 "Deamon %u started successfully\n", peer->id);
941   }
942
943   /* Find a peer to look for a string matching the regex announced */
944   search_peer = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
945                                           num_peers);
946   for (i = 0; peers[search_peer].search_str != NULL; i++)
947   {
948     search_peer = (search_peer + 1) % num_peers;
949     if (i > num_peers)
950       GNUNET_assert (0); /* we ran out of peers, must be a bug */
951   }
952   peers[search_peer].search_str = search_strings[peer->id];
953   peers[search_peer].search_str_matched = GNUNET_NO;
954   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply(
955                                   reannounce_period_max,
956                                   2),
957                                 &find_string,
958                                 (void *) search_peer);
959 }
960
961
962 /**
963  * Task to start the daemons on each peer so that the regexes are announced
964  * into the DHT.
965  *
966  * @param cls NULL
967  * @param tc the task context
968  */
969 static void
970 do_announce (void *cls)
971 {
972   unsigned int i;
973
974   if (GNUNET_YES == in_shutdown)
975     return;
976   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
977               "Starting announce.\n");
978   for (i = 0; i < init_parallel_searches; i++)
979   {
980     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
981                 "  scheduling announce %u\n",
982                 i);
983     (void) GNUNET_SCHEDULER_add_now (&announce_next_regex, NULL);
984   }
985 }
986
987
988 /**
989  * Start announcing the next regex in the DHT.
990  *
991  * @param cls Closure (unused).
992  */
993 static void
994 announce_next_regex (void *cls)
995 {
996   struct RegexPeer *peer;
997
998   if (GNUNET_YES == in_shutdown)
999     return;
1000   if (next_search >= num_peers)
1001   {
1002     if (strings_found != num_peers)
1003     {
1004       struct GNUNET_TIME_Relative new_delay;
1005       if (NULL != search_timeout_task)
1006         GNUNET_SCHEDULER_cancel (search_timeout_task);
1007       new_delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15);
1008       search_timeout_task = GNUNET_SCHEDULER_add_delayed (new_delay,
1009                                                           &search_timed_out,
1010                                                           NULL);
1011     }
1012     return;
1013   }
1014
1015   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Starting daemon %u\n", next_search);
1016   peer = &peers[next_search];
1017   peer->daemon_op =
1018   GNUNET_TESTBED_peer_manage_service (NULL,
1019                                       peer->peer_handle,
1020                                       "regexprofiler",
1021                                       &daemon_started,
1022                                       peer,
1023                                       1);
1024   next_search++;
1025   parallel_searches++;
1026 }
1027
1028
1029 /**
1030  * DHT connect callback. Called when we are connected to the dht service for
1031  * the peer in 'cls'. If successfull we connect to the stats service of this
1032  * peer and then try to match the search string of this peer.
1033  *
1034  * @param cls internal peer id.
1035  * @param op operation handle.
1036  * @param ca_result connect adapter result.
1037  * @param emsg error message.
1038  */
1039 static void
1040 dht_connect_cb (void *cls,
1041                 struct GNUNET_TESTBED_Operation *op,
1042                 void *ca_result,
1043                 const char *emsg)
1044 {
1045   struct RegexPeer *peer = (struct RegexPeer *) cls;
1046
1047   if (NULL != emsg || NULL == op || NULL == ca_result)
1048   {
1049     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "DHT connect failed: %s\n", emsg);
1050     GNUNET_assert (0);
1051   }
1052
1053   GNUNET_assert (NULL != peer->dht_handle);
1054   GNUNET_assert (peer->op_handle == op);
1055   GNUNET_assert (peer->dht_handle == ca_result);
1056
1057   peer->search_str_matched = GNUNET_NO;
1058   peer->search_handle = REGEX_INTERNAL_search (peer->dht_handle,
1059                                              peer->search_str,
1060                                              &regex_found_handler, peer,
1061                                              NULL);
1062   peer->prof_start_time = GNUNET_TIME_absolute_get ();
1063 }
1064
1065
1066 /**
1067  * DHT connect adapter. Opens a connection to the dht service.
1068  *
1069  * @param cls Closure (peer).
1070  * @param cfg Configuration handle.
1071  *
1072  * @return
1073  */
1074 static void *
1075 dht_ca (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg)
1076 {
1077   struct RegexPeer *peer = cls;
1078
1079   peer->dht_handle = GNUNET_DHT_connect (cfg, 32);
1080
1081   return peer->dht_handle;
1082 }
1083
1084
1085 /**
1086  * Adapter function called to destroy a connection to the dht service.
1087  *
1088  * @param cls Closure (peer).
1089  * @param op_result Service handle returned from the connect adapter.
1090  */
1091 static void
1092 dht_da (void *cls, void *op_result)
1093 {
1094   struct RegexPeer *peer = (struct RegexPeer *) cls;
1095
1096   GNUNET_assert (peer->dht_handle == op_result);
1097
1098   if (NULL != peer->search_handle)
1099   {
1100     REGEX_INTERNAL_search_cancel (peer->search_handle);
1101     peer->search_handle = NULL;
1102   }
1103
1104   if (NULL != peer->dht_handle)
1105   {
1106     GNUNET_DHT_disconnect (peer->dht_handle);
1107     peer->dht_handle = NULL;
1108   }
1109 }
1110
1111
1112 /**
1113  * Signature of a main function for a testcase.
1114  *
1115  * @param cls NULL
1116  * @param h the run handle
1117  * @param num_peers_ number of peers in 'peers'
1118  * @param testbed_peers handle to peers run in the testbed.  NULL upon timeout (see
1119  *          GNUNET_TESTBED_test_run()).
1120  * @param links_succeeded the number of overlay link connection attempts that
1121  *          succeeded
1122  * @param links_failed the number of overlay link connection attempts that
1123  *          failed
1124  */
1125 static void
1126 test_master (void *cls,
1127              struct GNUNET_TESTBED_RunHandle *h,
1128              unsigned int num_peers_,
1129              struct GNUNET_TESTBED_Peer **testbed_peers,
1130              unsigned int links_succeeded,
1131              unsigned int links_failed)
1132 {
1133   unsigned int i;
1134
1135   GNUNET_assert (num_peers_ == num_peers);
1136
1137   prof_time = GNUNET_TIME_absolute_get_duration (prof_start_time);
1138   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1139               "Testbed started in %s\n",
1140               GNUNET_STRINGS_relative_time_to_string (prof_time, GNUNET_NO));
1141
1142   if (NULL != abort_task)
1143   {
1144     GNUNET_SCHEDULER_cancel (abort_task);
1145     abort_task = NULL;
1146   }
1147
1148   for (i = 0; i < num_peers; i++)
1149   {
1150     peers[i].peer_handle = testbed_peers[i];
1151   }
1152   if (GNUNET_NO ==
1153       GNUNET_CONFIGURATION_get_value_yesno (cfg, "DHT", "DISABLE_TRY_CONNECT"))
1154   {
1155     struct GNUNET_TIME_Relative settle_time;
1156
1157     settle_time =
1158       GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1159                                      10 * num_peers);
1160     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1161                 "Waiting for DHT for %s to settle new connections.\n\n",
1162                 GNUNET_STRINGS_relative_time_to_string(settle_time, GNUNET_NO));
1163     GNUNET_SCHEDULER_add_delayed (settle_time, &do_announce, NULL);
1164   }
1165   else
1166   {
1167     GNUNET_SCHEDULER_add_now (&do_announce, NULL);
1168   }
1169   search_timeout_task =
1170       GNUNET_SCHEDULER_add_delayed (search_timeout_time, &search_timed_out, NULL);
1171 }
1172
1173 /**
1174  * Function that will be called whenever something in the testbed changes.
1175  *
1176  * @param cls closure, NULL
1177  * @param event information on what is happening
1178  */
1179 static void
1180 master_controller_cb (void *cls,
1181                       const struct GNUNET_TESTBED_EventInformation *event)
1182 {
1183   switch (event->type)
1184   {
1185   case GNUNET_TESTBED_ET_CONNECT:
1186     printf(".");
1187     break;
1188   case GNUNET_TESTBED_ET_PEER_START:
1189     printf("#");
1190     break;
1191   default:
1192     break;
1193   }
1194   fflush(stdout);
1195 }
1196
1197
1198 /******************************************************************************/
1199 /***************************  TESTBED PEER SETUP  *****************************/
1200 /******************************************************************************/
1201
1202
1203 /**
1204  * Load search strings from given filename. One search string per line.
1205  *
1206  * @param filename filename of the file containing the search strings.
1207  * @param strings set of strings loaded from file. Caller needs to free this
1208  *                if number returned is greater than zero.
1209  * @param limit upper limit on the number of strings read from the file
1210  * @return number of strings found in the file. #GNUNET_SYSERR on error.
1211  */
1212 static int
1213 load_search_strings (const char *filename,
1214                      char ***strings,
1215                      unsigned int limit)
1216 {
1217   char *data;
1218   char *buf;
1219   uint64_t filesize;
1220   unsigned int offset;
1221   int str_cnt;
1222   unsigned int i;
1223
1224   if (NULL == filename)
1225   {
1226     return GNUNET_SYSERR;
1227   }
1228
1229   if (GNUNET_YES != GNUNET_DISK_file_test (filename))
1230   {
1231     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1232                 "Could not find search strings file %s\n", filename);
1233     return GNUNET_SYSERR;
1234   }
1235   if (GNUNET_OK != GNUNET_DISK_file_size (filename, &filesize, GNUNET_YES, GNUNET_YES))
1236     filesize = 0;
1237   if (0 == filesize)
1238   {
1239     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Search strings file %s is empty.\n", filename);
1240     return GNUNET_SYSERR;
1241   }
1242   data = GNUNET_malloc (filesize);
1243   if (filesize != GNUNET_DISK_fn_read (filename, data, filesize))
1244   {
1245     GNUNET_free (data);
1246     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Could not read search strings file %s.\n",
1247          filename);
1248     return GNUNET_SYSERR;
1249   }
1250   buf = data;
1251   offset = 0;
1252   str_cnt = 0;
1253   while (offset < (filesize - 1) && str_cnt < limit)
1254   {
1255     offset++;
1256     if (((data[offset] == '\n')) && (buf != &data[offset]))
1257     {
1258       data[offset] = '\0';
1259       str_cnt++;
1260       buf = &data[offset + 1];
1261     }
1262     else if ((data[offset] == '\n') || (data[offset] == '\0'))
1263       buf = &data[offset + 1];
1264   }
1265   *strings = GNUNET_malloc (sizeof (char *) * str_cnt);
1266   offset = 0;
1267   for (i = 0; i < str_cnt; i++)
1268   {
1269     GNUNET_asprintf (&(*strings)[i], "%s%s", regex_prefix, &data[offset]);
1270     offset += strlen (&data[offset]) + 1;
1271   }
1272   GNUNET_free (data);
1273   return str_cnt;
1274 }
1275
1276
1277 /**
1278  * Main function that will be run by the scheduler.
1279  *
1280  * @param cls closure
1281  * @param args remaining command-line arguments
1282  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
1283  * @param config configuration
1284  */
1285 static void
1286 run (void *cls,
1287      char *const *args,
1288      const char *cfgfile,
1289      const struct GNUNET_CONFIGURATION_Handle *config)
1290 {
1291   unsigned int nsearchstrs;
1292   unsigned int i;
1293   struct GNUNET_TIME_Relative abort_time;
1294
1295   in_shutdown = GNUNET_NO;
1296
1297   /* Check config */
1298   if (NULL == config)
1299   {
1300     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1301                 _("No configuration file given. Exiting\n"));
1302     GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1303     return;
1304   }
1305   cfg = GNUNET_CONFIGURATION_dup (config);
1306   if (GNUNET_OK !=
1307       GNUNET_CONFIGURATION_get_value_string (cfg, "REGEXPROFILER",
1308                                              "REGEX_PREFIX",
1309                                              &regex_prefix))
1310   {
1311     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
1312                                "regexprofiler",
1313                                "regex_prefix");
1314     GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1315     return;
1316   }
1317   if (GNUNET_OK !=
1318       GNUNET_CONFIGURATION_get_value_number (cfg, "REGEXPROFILER",
1319                                              "PARALLEL_SEARCHES",
1320                                              &init_parallel_searches))
1321   {
1322     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1323                 "Configuration option \"PARALLEL_SEARCHES\" missing."
1324                 " Using default (%d)\n", 10);
1325     init_parallel_searches = 10;
1326   }
1327   if (GNUNET_OK !=
1328       GNUNET_CONFIGURATION_get_value_time (cfg, "REGEXPROFILER",
1329                                            "REANNOUNCE_PERIOD_MAX",
1330                                            &reannounce_period_max))
1331   {
1332     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1333                 "reannounce_period_max not given. Using 10 minutes.\n");
1334     reannounce_period_max =
1335       GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 10);
1336   }
1337
1338   /* Check arguments */
1339   if (NULL == policy_dir)
1340   {
1341     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1342                 _("No policy directory specified on command line. Exiting.\n"));
1343     return;
1344   }
1345   if (GNUNET_YES != GNUNET_DISK_directory_test (policy_dir, GNUNET_YES))
1346   {
1347     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1348                 _("Specified policies directory does not exist. Exiting.\n"));
1349     GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1350     return;
1351   }
1352   if (0 >= (int) (num_peers = GNUNET_DISK_directory_scan (policy_dir, NULL, NULL)))
1353   {
1354     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1355                 _("No files found in `%s'\n"),
1356                 policy_dir);
1357     return;
1358   }
1359   GNUNET_CONFIGURATION_set_value_string (cfg, "REGEXPROFILER",
1360                                          "POLICY_DIR", policy_dir);
1361   if (GNUNET_YES != GNUNET_DISK_file_test (strings_file))
1362   {
1363     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1364                 _("No search strings file given. Exiting.\n"));
1365     GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1366     return;
1367   }
1368   nsearchstrs = load_search_strings (strings_file,
1369                                      &search_strings,
1370                                      num_peers);
1371   if (num_peers != nsearchstrs)
1372   {
1373     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1374                 "Error loading search strings.\n");
1375     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1376                 "File (%s) does not contain enough strings (%u/%u).\n",
1377                 strings_file, nsearchstrs, num_peers);
1378     GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1379     return;
1380   }
1381   if ( (0 == num_peers) || (NULL == search_strings))
1382   {
1383     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1384                 _("Error loading search strings. Exiting.\n"));
1385     GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1386     return;
1387   }
1388   for (i = 0; i < num_peers; i++)
1389     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1390                 "search string: %s\n",
1391                 search_strings[i]);
1392
1393   /* Check logfile */
1394   if ( (NULL != data_filename) &&
1395        (NULL == (data_file =
1396                  GNUNET_DISK_file_open (data_filename,
1397                                         GNUNET_DISK_OPEN_READWRITE |
1398                                         GNUNET_DISK_OPEN_TRUNCATE |
1399                                         GNUNET_DISK_OPEN_CREATE,
1400                                         GNUNET_DISK_PERM_USER_READ |
1401                                         GNUNET_DISK_PERM_USER_WRITE))) )
1402   {
1403     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
1404                               "open",
1405                               data_filename);
1406     return;
1407   }
1408
1409   /* Initialize peers */
1410   peers = GNUNET_malloc (sizeof (struct RegexPeer) * num_peers);
1411   for (i = 0; i < num_peers; i++)
1412     peers[i].id = i;
1413
1414   GNUNET_CONFIGURATION_set_value_number (cfg,
1415                                          "TESTBED", "OVERLAY_RANDOM_LINKS",
1416                                          num_peers * 20);
1417   GNUNET_CONFIGURATION_set_value_number (cfg,
1418                                          "DHT", "FORCE_NSE",
1419                                          (long long unsigned)
1420                                          (log (num_peers) / log (2.0)));
1421   event_mask = 0LL;
1422 /* For feedback about the start process activate these and pass master_cb */
1423   event_mask |= (1LL << GNUNET_TESTBED_ET_PEER_START);
1424 //   event_mask |= (1LL << GNUNET_TESTBED_ET_PEER_STOP);
1425   event_mask |= (1LL << GNUNET_TESTBED_ET_CONNECT);
1426 //   event_mask |= (1LL << GNUNET_TESTBED_ET_DISCONNECT);
1427   prof_start_time = GNUNET_TIME_absolute_get ();
1428   GNUNET_TESTBED_run (hosts_file,
1429                       cfg,
1430                       num_peers,
1431                       event_mask,
1432                       &master_controller_cb,
1433                       NULL,     /* master_controller_cb cls */
1434                       &test_master,
1435                       NULL);    /* test_master cls */
1436   if (GNUNET_OK !=
1437       GNUNET_CONFIGURATION_get_value_time (cfg, "TESTBED",
1438                                            "SETUP_TIMEOUT",
1439                                            &abort_time))
1440   {
1441     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1442                 "SETUP_TIMEOUT not given. Using 15 minutes.\n");
1443     abort_time =
1444       GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15);
1445   }
1446   abort_time = GNUNET_TIME_relative_add (abort_time, GNUNET_TIME_UNIT_MINUTES);
1447   abort_task =
1448       GNUNET_SCHEDULER_add_delayed (abort_time,
1449                                     &do_abort,
1450                                     (void*) __LINE__);
1451   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1452               "setup_timeout: %s\n",
1453               GNUNET_STRINGS_relative_time_to_string (abort_time, GNUNET_YES));
1454 }
1455
1456
1457 /**
1458  * Main function.
1459  *
1460  * @param argc argument count
1461  * @param argv argument values
1462  * @return 0 on success
1463  */
1464 int
1465 main (int argc, char *const *argv)
1466 {
1467   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
1468     {'o', "output-file", "FILENAME",
1469      gettext_noop ("name of the file for writing statistics"),
1470      GNUNET_YES, &GNUNET_GETOPT_set_string, &data_filename},
1471     {'t', "matching-timeout", "TIMEOUT",
1472       gettext_noop ("wait TIMEOUT before ending the experiment"),
1473       GNUNET_YES, &GNUNET_GETOPT_set_relative_time, &search_timeout_time},
1474     {'p', "policy-dir", "DIRECTORY",
1475       gettext_noop ("directory with policy files"),
1476       GNUNET_YES, &GNUNET_GETOPT_set_filename, &policy_dir},
1477     {'s', "strings-file", "FILENAME",
1478       gettext_noop ("name of file with input strings"),
1479       GNUNET_YES, &GNUNET_GETOPT_set_filename, &strings_file},
1480     {'H', "hosts-file", "FILENAME",
1481       gettext_noop ("name of file with hosts' names"),
1482       GNUNET_YES, &GNUNET_GETOPT_set_filename, &hosts_file},
1483     GNUNET_GETOPT_OPTION_END
1484   };
1485   int ret;
1486
1487   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
1488     return 2;
1489   result = GNUNET_SYSERR;
1490   ret =
1491       GNUNET_PROGRAM_run (argc, argv,
1492                           "gnunet-regex-profiler",
1493                           _("Profiler for regex"),
1494                           options, &run, NULL);
1495   if (GNUNET_OK != ret)
1496     return ret;
1497   if (GNUNET_OK != result)
1498     return 1;
1499   return 0;
1500 }