- remove old internal testbed code
[oweals/gnunet.git] / src / regex / gnunet-regex-profiler.c
1 /*
2      This file is part of GNUnet.
3      (C) 2011 - 2013 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file regex/gnunet-regex-profiler.c
23  * @brief Regex profiler for testing distributed regex use.
24  * @author Bartlomiej Polot
25  * @author Maximilian Szengel
26  *
27  */
28
29 #include <string.h>
30
31 #include "platform.h"
32 #include "gnunet_applications.h"
33 #include "gnunet_util_lib.h"
34 #include "gnunet_regex_lib.h"
35 #include "gnunet_arm_service.h"
36 #include "gnunet_dht_service.h"
37 #include "gnunet_testbed_service.h"
38
39 #define FIND_TIMEOUT \
40         GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 90)
41 #define SEARCHES_IN_PARALLEL 5
42
43 /**
44  * DLL of operations
45  */
46 struct DLLOperation
47 {
48   /**
49    * The testbed operation handle
50    */
51   struct GNUNET_TESTBED_Operation *op;
52
53   /**
54    * Closure
55    */
56   void *cls;
57
58   /**
59    * The next pointer for DLL
60    */
61   struct DLLOperation *next;
62
63   /**
64    * The prev pointer for DLL
65    */
66   struct DLLOperation *prev;
67 };
68
69
70 /**
71  * Available states during profiling
72  */
73 enum State
74 {
75   /**
76    * Initial state
77    */
78   STATE_INIT = 0,
79
80   /**
81    * Starting slaves
82    */
83   STATE_SLAVES_STARTING,
84
85   /**
86    * Creating peers
87    */
88   STATE_PEERS_CREATING,
89
90   /**
91    * Starting peers
92    */
93   STATE_PEERS_STARTING,
94
95   /**
96    * Linking peers
97    */
98   STATE_PEERS_LINKING,
99
100   /**
101    * Matching strings against announced regexes
102    */
103   STATE_SEARCH_REGEX,
104
105   /**
106    * Destroying peers; we can do this as the controller takes care of stopping a
107    * peer if it is running
108    */
109   STATE_PEERS_DESTROYING
110 };
111
112
113 /**
114  * Peer handles.
115  */
116 struct RegexPeer
117 {
118   /**
119    * Peer id.
120    */
121   unsigned int id;
122
123   /**
124    * Peer configuration handle.
125    */
126   struct GNUNET_CONFIGURATION_Handle *cfg;
127
128   /**
129    * The actual testbed peer handle.
130    */
131   struct GNUNET_TESTBED_Peer *peer_handle;
132
133   /**
134    * Host on which the peer is running.
135    */
136   struct GNUNET_TESTBED_Host *host_handle;
137
138   /**
139    * Filename of the peer's policy file.
140    */
141   char *policy_file;
142
143   /**
144    * Peer's search string.
145    */
146   const char *search_str;
147
148   /**
149    * Set to GNUNET_YES if the peer successfully matched the above
150    * search string. GNUNET_NO if the string could not be matched
151    * during the profiler run. GNUNET_SYSERR if the string matching
152    * timed out. Undefined if search_str is NULL
153    */
154   int search_str_matched;
155
156   /**
157    * Peer's DHT handle.
158    */
159   struct GNUNET_DHT_Handle *dht_handle;
160
161   /**
162    * Handle to a running regex search.
163    */
164    struct GNUNET_REGEX_search_handle *search_handle;
165
166   /**
167    * Testbed operation handle for DHT.
168    */
169   struct GNUNET_TESTBED_Operation *op_handle;
170
171   /**
172    * Peers's statistics handle.
173    */
174   struct GNUNET_STATISTICS_Handle *stats_handle;
175
176   /**
177    * Testbed operation handle for the statistics service.
178    */
179   struct GNUNET_TESTBED_Operation *stats_op_handle;
180
181   /**
182    * The starting time of a profiling step.
183    */
184   struct GNUNET_TIME_Absolute prof_start_time;
185
186   /**
187    * Operation timeout
188    */
189   GNUNET_SCHEDULER_TaskIdentifier timeout;
190
191   /**
192    * Deamon start
193    */
194   struct GNUNET_TESTBED_Operation *daemon_op;
195 };
196
197
198 /**
199  * The array of peers; we fill this as the peers are given to us by the testbed
200  */
201 static struct RegexPeer *peers;
202
203 /**
204  * Host registration handle
205  */
206 static struct GNUNET_TESTBED_HostRegistrationHandle *reg_handle;
207
208 /**
209  * Handle to the master controller process
210  */
211 static struct GNUNET_TESTBED_ControllerProc *mc_proc;
212
213 /**
214  * Handle to the master controller
215  */
216 static struct GNUNET_TESTBED_Controller *mc;
217
218 /**
219  * Handle to global configuration
220  */
221 static struct GNUNET_CONFIGURATION_Handle *cfg;
222
223 /**
224  * Abort task identifier
225  */
226 static GNUNET_SCHEDULER_TaskIdentifier abort_task;
227
228 /**
229  * Shutdown task identifier
230  */
231 static GNUNET_SCHEDULER_TaskIdentifier shutdown_task;
232
233 /**
234  * Host registration task identifier
235  */
236 static GNUNET_SCHEDULER_TaskIdentifier register_hosts_task;
237
238 /**
239  * Global event mask for all testbed events
240  */
241 static uint64_t event_mask;
242
243 /**
244  * The starting time of a profiling step
245  */
246 static struct GNUNET_TIME_Absolute prof_start_time;
247
248 /**
249  * Duration profiling step has taken
250  */
251 static struct GNUNET_TIME_Relative prof_time;
252
253 /**
254  * Number of peers to be started by the profiler
255  */
256 static unsigned int num_peers;
257
258 /**
259  * Factor of number of links. num_links = num_peers * linking_factor.
260  */
261 static unsigned int linking_factor;
262
263 /**
264  * Global testing status
265  */
266 static int result;
267
268 /**
269  * current state of profiling
270  */
271 enum State state;
272
273 /**
274  * Folder where policy files are stored.
275  */
276 static char * policy_dir;
277
278 /**
279  * Search strings.
280  */
281 static char **search_strings;
282
283 /**
284  * Number of search strings.
285  */
286 static int num_search_strings;
287
288 /**
289  * How many searches are running in parallel
290  */
291 static unsigned int parallel_searches;
292
293 /**
294  * Number of peers found with search strings.
295  */
296 static unsigned int peers_found;
297
298 /**
299  * Index of peer to start next announce/search.
300  */
301 static unsigned int next_search;
302
303 /**
304  * Search timeout task identifier.
305  */
306 static GNUNET_SCHEDULER_TaskIdentifier search_timeout_task;
307
308 /**
309  * Search timeout in seconds.
310  */
311 static struct GNUNET_TIME_Relative search_timeout_time = { 60000 };
312
313 /**
314  * How long do we wait before starting the search?
315  * Default: 1 m.
316  */
317 static struct GNUNET_TIME_Relative search_delay = { 60000 };
318
319 /**
320  * File to log statistics to.
321  */
322 static struct GNUNET_DISK_FileHandle *data_file;
323
324 /**
325  * Filename to log statistics to.
326  */
327 static char *data_filename;
328
329 /**
330  * Maximal path compression length.
331  */
332 static unsigned int max_path_compression;
333
334 /**
335  * Prefix used for regex announcing. We need to prefix the search
336  * strings with it, in order to find something.
337  */
338 static char * regex_prefix;
339
340 /**
341  * What's the maximum regex reannounce period.
342  */
343 static struct GNUNET_TIME_Relative reannounce_period_max;
344
345
346 /******************************************************************************/
347 /******************************  DECLARATIONS  ********************************/
348 /******************************************************************************/
349
350 /**
351  * DHT connect callback.
352  *
353  * @param cls internal peer id.
354  * @param op operation handle.
355  * @param ca_result connect adapter result.
356  * @param emsg error message.
357  */
358 static void
359 dht_connect_cb (void *cls, struct GNUNET_TESTBED_Operation *op,
360                 void *ca_result, const char *emsg);
361
362 /**
363  * DHT connect adapter.
364  *
365  * @param cls not used.
366  * @param cfg configuration handle.
367  *
368  * @return
369  */
370 static void *
371 dht_ca (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg);
372
373
374 /**
375  * Adapter function called to destroy a connection to
376  * the DHT service
377  *
378  * @param cls closure
379  * @param op_result service handle returned from the connect adapter
380  */
381 static void
382 dht_da (void *cls, void *op_result);
383
384
385 /**
386  * Function called by testbed once we are connected to stats
387  * service. Get the statistics for the services of interest.
388  *
389  * @param cls the 'struct RegexPeer' for which we connected to stats
390  * @param op connect operation handle
391  * @param ca_result handle to stats service
392  * @param emsg error message on failure
393  */
394 static void
395 stats_connect_cb (void *cls,
396                   struct GNUNET_TESTBED_Operation *op,
397                   void *ca_result,
398                   const char *emsg);
399
400
401 /**
402  * Task to collect all statistics from s, will shutdown the
403  * profiler, when done.
404  *
405  * @param cls NULL
406  * @param tc the task context
407  */
408 static void
409 do_collect_stats (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
410
411
412 /**
413  * Start announcing the next regex in the DHT.
414  *
415  * @param cls Index of the next peer in the peers array.
416  * @param tc TaskContext.
417  */
418 static void
419 announce_next_regex (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
420
421
422 /******************************************************************************/
423 /********************************  SHUTDOWN  **********************************/
424 /******************************************************************************/
425
426
427 /**
428  * Shutdown nicely
429  *
430  * @param cls NULL
431  * @param tc the task context
432  */
433 static void
434 do_shutdown (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
435 {
436   struct RegexPeer *peer;
437   unsigned int peer_cnt;
438   unsigned int search_str_cnt;
439   char output_buffer[512];
440   size_t size;
441
442   shutdown_task = GNUNET_SCHEDULER_NO_TASK;
443   if (GNUNET_SCHEDULER_NO_TASK != abort_task)
444     GNUNET_SCHEDULER_cancel (abort_task);
445   if (GNUNET_SCHEDULER_NO_TASK != register_hosts_task)
446     GNUNET_SCHEDULER_cancel (register_hosts_task);
447
448   for (peer_cnt = 0; peer_cnt < num_peers; peer_cnt++)
449   {
450     peer = &peers[peer_cnt];
451
452     if (GNUNET_YES != peer->search_str_matched && NULL != data_file)
453     {
454       prof_time = GNUNET_TIME_absolute_get_duration (peer->prof_start_time);
455       size =
456         GNUNET_snprintf (output_buffer,
457                          sizeof (output_buffer),
458                          "%p Search string not found: %s (%d)\n%p On peer: %u (%p)\n%p With policy file: %s\n%p After: %s\n",
459                          peer, peer->search_str, peer->search_str_matched,
460                          peer, peer->id, peer,
461                          peer, peer->policy_file,
462                          peer,
463                          GNUNET_STRINGS_relative_time_to_string (prof_time,
464                                                                  GNUNET_NO));
465       if (size != GNUNET_DISK_file_write (data_file, output_buffer, size))
466         GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Unable to write to file!\n");
467     }
468
469     if (NULL != peers[peer_cnt].op_handle)
470       GNUNET_TESTBED_operation_done (peers[peer_cnt].op_handle);
471     if (NULL != peers[peer_cnt].stats_op_handle)
472       GNUNET_TESTBED_operation_done (peers[peer_cnt].stats_op_handle);
473   }
474
475   if (NULL != data_file)
476     GNUNET_DISK_file_close (data_file);
477
478   for (search_str_cnt = 0;
479        search_str_cnt < num_search_strings && NULL != search_strings;
480        search_str_cnt++)
481   {
482     GNUNET_free_non_null (search_strings[search_str_cnt]);
483   }
484   GNUNET_free_non_null (search_strings);
485
486   if (NULL != reg_handle)
487     GNUNET_TESTBED_cancel_registration (reg_handle);
488
489   if (NULL != mc)
490     GNUNET_TESTBED_controller_disconnect (mc);
491   if (NULL != mc_proc)
492     GNUNET_TESTBED_controller_stop (mc_proc);
493   if (NULL != cfg)
494     GNUNET_CONFIGURATION_destroy (cfg);
495
496   GNUNET_SCHEDULER_shutdown (); /* Stop scheduler to shutdown testbed run */
497 }
498
499
500 /**
501  * abort task to run on test timed out
502  *
503  * @param cls NULL
504  * @param tc the task context
505  */
506 static void
507 do_abort (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
508 {
509   unsigned long i = (unsigned long) cls;
510
511   GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Aborting %lu...\n", i);
512   abort_task = GNUNET_SCHEDULER_NO_TASK;
513   result = GNUNET_SYSERR;
514   if (GNUNET_SCHEDULER_NO_TASK != shutdown_task)
515     GNUNET_SCHEDULER_cancel (shutdown_task);
516   shutdown_task = GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
517 }
518
519
520 /******************************************************************************/
521 /*********************  STATISTICS SERVICE CONNECTIONS  ***********************/
522 /******************************************************************************/
523
524 /**
525  * Adapter function called to establish a connection to
526  * statistics service.
527  *
528  * @param cls closure
529  * @param cfg configuration of the peer to connect to; will be available until
530  *          GNUNET_TESTBED_operation_done() is called on the operation returned
531  *          from GNUNET_TESTBED_service_connect()
532  * @return service handle to return in 'op_result', NULL on error
533  */
534 static void *
535 stats_ca (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg)
536 {
537   return GNUNET_STATISTICS_create ("<driver>", cfg);
538 }
539
540
541 /**
542  * Adapter function called to destroy a connection to
543  * statistics service.
544  *
545  * @param cls closure
546  * @param op_result service handle returned from the connect adapter
547  */
548 static void
549 stats_da (void *cls, void *op_result)
550 {
551   struct RegexPeer *peer = cls;
552
553   GNUNET_assert (op_result == peer->stats_handle);
554
555   GNUNET_STATISTICS_destroy (peer->stats_handle, GNUNET_NO);
556   peer->stats_handle = NULL;
557 }
558
559
560 /**
561  * Process statistic values. Write all values to global 'data_file', if present.
562  *
563  * @param cls closure
564  * @param subsystem name of subsystem that created the statistic
565  * @param name the name of the datum
566  * @param value the current value
567  * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
568  * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
569  */
570 static int
571 stats_iterator (void *cls, const char *subsystem, const char *name,
572                 uint64_t value, int is_persistent)
573 {
574   struct RegexPeer *peer = cls;
575   char output_buffer[512];
576   size_t size;
577
578   if (NULL == data_file)
579   {
580     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
581                 "%p -> %s [%s]: %llu\n",
582                 peer, subsystem, name, value);
583     return GNUNET_OK;
584   }
585   size =
586     GNUNET_snprintf (output_buffer,
587                      sizeof (output_buffer),
588                      "%p [%s] %llu %s\n",
589                      peer,
590                      subsystem, value, name);
591   if (size != GNUNET_DISK_file_write (data_file, output_buffer, size))
592     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Unable to write to file!\n");
593
594   return GNUNET_OK;
595 }
596
597
598 /**
599  * Stats callback. Finish the stats testbed operation and when all stats have
600  * been iterated, shutdown the profiler.
601  *
602  * @param cls closure
603  * @param success GNUNET_OK if statistics were
604  *        successfully obtained, GNUNET_SYSERR if not.
605  */
606 static void
607 stats_cb (void *cls,
608           int success)
609 {
610   static unsigned int peer_cnt;
611   struct RegexPeer *peer = cls;
612
613   if (GNUNET_OK != success)
614   {
615     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
616                 "Getting statistics for peer %u failed!\n",
617                 peer->id);
618     return;
619   }
620
621   GNUNET_assert (NULL != peer->stats_op_handle);
622
623   GNUNET_TESTBED_operation_done (peer->stats_op_handle);
624   peer->stats_op_handle = NULL;
625
626   peer_cnt++;
627   peer = &peers[peer_cnt];
628
629   if (peer_cnt == num_peers)
630   {
631     struct GNUNET_TIME_Relative delay = { 100 };
632     shutdown_task = GNUNET_SCHEDULER_add_delayed (delay, &do_shutdown, NULL);
633   }
634   else
635   {
636     peer->stats_op_handle =
637       GNUNET_TESTBED_service_connect (NULL,
638                                       peer->peer_handle,
639                                       "statistics",
640                                       &stats_connect_cb,
641                                       peer,
642                                       &stats_ca,
643                                       &stats_da,
644                                       peer);
645   }
646 }
647
648
649 /**
650  * Function called by testbed once we are connected to stats
651  * service. Get the statistics for the services of interest.
652  *
653  * @param cls the 'struct RegexPeer' for which we connected to stats
654  * @param op connect operation handle
655  * @param ca_result handle to stats service
656  * @param emsg error message on failure
657  */
658 static void
659 stats_connect_cb (void *cls,
660                   struct GNUNET_TESTBED_Operation *op,
661                   void *ca_result,
662                   const char *emsg)
663 {
664   struct RegexPeer *peer = cls;
665
666   if (NULL == ca_result || NULL != emsg)
667   {
668     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
669                 "Failed to connect to statistics service on peer %u: %s\n",
670                 peer->id, emsg);
671
672     peer->stats_handle = NULL;
673     return;
674   }
675
676   peer->stats_handle = ca_result;
677
678   if (NULL == GNUNET_STATISTICS_get (peer->stats_handle, NULL, NULL,
679                                      GNUNET_TIME_UNIT_FOREVER_REL,
680                                      &stats_cb,
681                                      &stats_iterator, peer))
682   {
683     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
684                 "Could not get statistics of peer %u!\n", peer->id);
685   }
686 }
687
688
689 /**
690  * Task to collect all statistics from all peers, will shutdown the
691  * profiler, when done.
692  *
693  * @param cls NULL
694  * @param tc the task context
695  */
696 static void
697 do_collect_stats (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
698 {
699   struct RegexPeer *peer = &peers[0];
700
701   GNUNET_assert (NULL != peer->peer_handle);
702
703   peer->stats_op_handle =
704     GNUNET_TESTBED_service_connect (NULL,
705                                     peer->peer_handle,
706                                     "statistics",
707                                     &stats_connect_cb,
708                                     peer,
709                                     &stats_ca,
710                                     &stats_da,
711                                     peer);
712 }
713
714
715 /******************************************************************************/
716 /************************   REGEX FIND CONNECTIONS   **************************/
717 /******************************************************************************/
718
719
720 /**
721  * Start searching for the next string in the DHT.
722  *
723  * @param cls Index of the next peer in the peers array.
724  * @param tc TaskContext.
725  */
726 static void
727 find_string (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
728
729
730 /**
731  * Method called when we've found a peer that announced a regex
732  * that matches our search string. Now get the statistics.
733  *
734  * @param cls Closure provided in GNUNET_REGEX_search.
735  * @param id Peer providing a regex that matches the string.
736  * @param get_path Path of the get request.
737  * @param get_path_length Lenght of get_path.
738  * @param put_path Path of the put request.
739  * @param put_path_length Length of the put_path.
740  */
741 static void
742 regex_found_handler (void *cls,
743                      const struct GNUNET_PeerIdentity *id,
744                      const struct GNUNET_PeerIdentity *get_path,
745                      unsigned int get_path_length,
746                      const struct GNUNET_PeerIdentity *put_path,
747                      unsigned int put_path_length)
748 {
749   struct RegexPeer *peer = cls;
750   char output_buffer[512];
751   size_t size;
752
753   if (GNUNET_YES == peer->search_str_matched)
754   {
755     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
756                 "String %s on peer %u already matched!\n",
757                 peer->search_str, peer->id);
758     return;
759   }
760
761   peers_found++;
762   parallel_searches--;
763
764   if (GNUNET_SCHEDULER_NO_TASK != peer->timeout)
765   {
766     GNUNET_SCHEDULER_cancel (peer->timeout);
767     peer->timeout = GNUNET_SCHEDULER_NO_TASK;
768     GNUNET_SCHEDULER_add_now (&announce_next_regex, NULL);
769   }
770
771   if (NULL == id)
772   {
773     // FIXME not possible right now
774     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
775                 "String matching timed out for string %s on peer %u (%i/%i)\n",
776                 peer->search_str, peer->id, peers_found, num_search_strings);
777     peer->search_str_matched = GNUNET_SYSERR;
778   }
779   else
780   {
781     prof_time = GNUNET_TIME_absolute_get_duration (peer->prof_start_time);
782
783     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
784                 "String %s found on peer %u after %s (%i/%i) (%u||)\n",
785                 peer->search_str, peer->id,
786                 GNUNET_STRINGS_relative_time_to_string (prof_time, GNUNET_NO),
787                 peers_found, num_search_strings, parallel_searches);
788
789     peer->search_str_matched = GNUNET_YES;
790
791     if (NULL != data_file)
792     {
793       size =
794         GNUNET_snprintf (output_buffer,
795                          sizeof (output_buffer),
796                          "%p Peer: %u\n%p Host: %s\n%p Policy file: %s\n"
797                          "%p Search string: %s\n%p Search duration: %s\n\n",
798                          peer, peer->id,
799                          peer,
800                          GNUNET_TESTBED_host_get_hostname (peer->host_handle),
801                          peer, peer->policy_file,
802                          peer, peer->search_str,
803                          peer,
804                          GNUNET_STRINGS_relative_time_to_string (prof_time,
805                                                                  GNUNET_NO));
806
807       if (size != GNUNET_DISK_file_write (data_file, output_buffer, size))
808         GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Unable to write to file!\n");
809     }
810   }
811
812   GNUNET_TESTBED_operation_done (peer->op_handle);
813   peer->op_handle = NULL;
814
815   if (peers_found == num_search_strings)
816   {
817     prof_time = GNUNET_TIME_absolute_get_duration (prof_start_time);
818     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
819                 "All strings successfully matched in %s\n",
820                 GNUNET_STRINGS_relative_time_to_string (prof_time, GNUNET_NO));
821
822     if (GNUNET_SCHEDULER_NO_TASK != search_timeout_task)
823       GNUNET_SCHEDULER_cancel (search_timeout_task);
824
825     GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Collecting stats and shutting down.\n");
826     GNUNET_SCHEDULER_add_now (&do_collect_stats, NULL);
827   }
828 }
829
830
831 /**
832  * Connect by string timeout task. This will cancel the profiler after the
833  * specified timeout 'search_timeout'.
834  *
835  * @param cls NULL
836  * @param tc the task context
837  */
838 static void
839 search_timeout (void *cls,
840                               const struct GNUNET_SCHEDULER_TaskContext * tc)
841 {
842   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
843               "Finding matches to all strings did not succeed after %s.\n",
844               GNUNET_STRINGS_relative_time_to_string (search_timeout_time,
845                                                       GNUNET_NO));
846   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
847               "Found %i of %i strings\n", peers_found, num_search_strings);
848
849   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
850               "Search timed out after %s."
851               "Collecting stats and shutting down.\n", 
852               GNUNET_STRINGS_relative_time_to_string (search_timeout_time,
853                                                       GNUNET_NO));
854
855   GNUNET_SCHEDULER_add_now (&do_collect_stats, NULL);
856 }
857
858
859 /**
860  * Search timed out. It might still complete in the future,
861  * but we should start another one.
862  *
863  * @param cls Index of the next peer in the peers array.
864  * @param tc TaskContext.
865  */
866 static void
867 find_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
868 {
869   struct RegexPeer *p = cls;
870
871   p->timeout = GNUNET_SCHEDULER_NO_TASK;
872
873   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
874     return;
875   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
876               "Searching for string \"%s\" on peer %d timed out. Starting new search.\n",
877               p->search_str,
878               p->id);
879   GNUNET_SCHEDULER_add_now (&announce_next_regex, NULL);
880 }
881
882
883 /**
884  * Start searching for a string in the DHT.
885  *
886  * @param cls Index of the next peer in the peers array.
887  * @param tc TaskContext.
888  */
889 static void
890 find_string (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
891 {
892   unsigned int search_peer = (unsigned int) (long) cls;
893
894   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) ||
895       search_peer >= num_search_strings)
896     return;
897
898   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
899               "Searching for string \"%s\" on peer %d with file %s (%u||)\n",
900               peers[search_peer].search_str,
901               search_peer,
902               peers[search_peer].policy_file,
903               parallel_searches);
904
905   peers[search_peer].op_handle =
906     GNUNET_TESTBED_service_connect (NULL,
907                                     peers[search_peer].peer_handle,
908                                     "dht",
909                                     &dht_connect_cb,
910                                     &peers[search_peer],
911                                     &dht_ca,
912                                     &dht_da,
913                                     &peers[search_peer]);
914   GNUNET_assert (NULL != peers[search_peer].op_handle);
915   peers[search_peer].timeout = GNUNET_SCHEDULER_add_delayed (FIND_TIMEOUT,
916                                                           &find_timeout,
917                                                           &peers[search_peer]);
918 }
919
920
921
922
923 /**
924  * Callback called when testbed has started the daemon we asked for.
925  *
926  * @param cls NULL
927  * @param op the operation handle
928  * @param emsg NULL on success; otherwise an error description
929  */
930 static void
931 daemon_started (void *cls, struct GNUNET_TESTBED_Operation *op,
932                 const char *emsg)
933 {
934   struct RegexPeer *peer = (struct RegexPeer *) cls;
935   unsigned long search_peer;
936   unsigned int i;
937   unsigned int me;
938
939   GNUNET_TESTBED_operation_done (peer->daemon_op);
940   me = peer - peers;
941   if (NULL != emsg)
942   {
943     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
944                 "Failed to start/stop daemon at peer %u: %s\n", me, emsg);
945     GNUNET_abort ();
946   }
947
948   /* Find a peer to look for a string matching the regex announced */
949   search_peer = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
950                                           num_peers);
951   for (i = 0; peers[search_peer].search_str != NULL; i++)
952   {
953     search_peer = (search_peer + 1) % num_peers;
954     if (i > num_peers)
955       GNUNET_abort (); /* we ran out of peers, must be a bug */
956   }
957   peers[search_peer].search_str = search_strings[me];
958   peers[search_peer].search_str_matched = GNUNET_NO;
959   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply(
960                                   reannounce_period_max,
961                                   2),
962                                 &find_string,
963                                 (void *) search_peer);
964   if (next_search >= num_peers &&
965       GNUNET_SCHEDULER_NO_TASK == search_timeout_task)
966   {
967     GNUNET_log (GNUNET_ERROR_TYPE_INFO, "All daemons started.\n");
968     /* FIXME start GLOBAL timeout to abort experiment */
969     search_timeout_task = GNUNET_SCHEDULER_add_delayed (search_timeout_time,
970                                                         &search_timeout,
971                                                         NULL);
972   }
973 }
974
975
976 /**
977  * Task to start the daemons on each peer so that the regexes are announced
978  * into the DHT.
979  *
980  * @param cls NULL
981  * @param tc the task context
982  */
983 static void
984 do_announce (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
985 {
986   unsigned int i;
987
988   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Starting announce.\n");
989
990   for (i = 0; i < SEARCHES_IN_PARALLEL; i++)
991   {
992     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
993                 "  scheduling announce %u\n",
994                 i);
995     (void) GNUNET_SCHEDULER_add_now (&announce_next_regex, NULL);
996   }
997 }
998
999
1000 /**
1001  * Start announcing the next regex in the DHT.
1002  *
1003  * @param cls Closure (unused).
1004  * @param tc TaskContext.
1005  */
1006 static void
1007 announce_next_regex (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1008 {
1009   struct RegexPeer *peer;
1010
1011   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) ||
1012             next_search >= num_peers)
1013     return;
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  * 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, struct GNUNET_TESTBED_Operation *op,
1040                 void *ca_result, const char *emsg)
1041 {
1042   struct RegexPeer *peer = (struct RegexPeer *) cls;
1043
1044   if (NULL != emsg || NULL == op || NULL == ca_result)
1045   {
1046     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "DHT connect failed: %s\n", emsg);
1047     GNUNET_abort ();
1048   }
1049
1050   GNUNET_assert (NULL != peer->dht_handle);
1051   GNUNET_assert (peer->op_handle == op);
1052   GNUNET_assert (peer->dht_handle == ca_result);
1053
1054   peer->search_str_matched = GNUNET_NO;
1055   peer->search_handle = GNUNET_REGEX_search (peer->dht_handle,
1056                                              peer->search_str,
1057                                              &regex_found_handler, peer,
1058                                              NULL);
1059   peer->prof_start_time = GNUNET_TIME_absolute_get ();
1060 }
1061
1062
1063 /**
1064  * DHT connect adapter. Opens a connection to the dht service.
1065  *
1066  * @param cls Closure (peer).
1067  * @param cfg Configuration handle.
1068  *
1069  * @return
1070  */
1071 static void *
1072 dht_ca (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg)
1073 {
1074   struct RegexPeer *peer = cls;
1075
1076   peer->dht_handle = GNUNET_DHT_connect (cfg, 32);
1077
1078   return peer->dht_handle;
1079 }
1080
1081
1082 /**
1083  * Adapter function called to destroy a connection to the dht service.
1084  *
1085  * @param cls Closure (peer).
1086  * @param op_result Service handle returned from the connect adapter.
1087  */
1088 static void
1089 dht_da (void *cls, void *op_result)
1090 {
1091   struct RegexPeer *peer = (struct RegexPeer *) cls;
1092
1093   GNUNET_assert (peer->dht_handle == op_result);
1094
1095   if (NULL != peer->search_handle)
1096   {
1097     GNUNET_REGEX_search_cancel (peer->search_handle);
1098     peer->search_handle = NULL;
1099   }
1100
1101   if (NULL != peer->dht_handle)
1102   {
1103     GNUNET_DHT_disconnect (peer->dht_handle);
1104     peer->dht_handle = NULL;
1105   }
1106 }
1107
1108
1109 /**
1110  * Signature of a main function for a testcase.
1111  *
1112  * @param cls NULL
1113  * @param num_peers_ number of peers in 'peers'
1114  * @param peers handle to peers run in the testbed.  NULL upon timeout (see
1115  *          GNUNET_TESTBED_test_run()).
1116  * @param links_succeeded the number of overlay link connection attempts that
1117  *          succeeded
1118  * @param links_failed the number of overlay link connection attempts that
1119  *          failed
1120  */
1121 static void 
1122 test_master (void *cls,
1123              unsigned int num_peers_,
1124              struct GNUNET_TESTBED_Peer **testbed_peers,
1125              unsigned int links_succeeded,
1126              unsigned int links_failed)
1127 {
1128   unsigned int i;
1129
1130   for (i = 0; i < num_peers; i++) 
1131   GNUNET_SCHEDULER_add_now (&do_announce, NULL);
1132 }
1133
1134
1135 /******************************************************************************/
1136 /***************************  TESTBED PEER SETUP  *****************************/
1137 /******************************************************************************/
1138
1139
1140 /**
1141  * Load search strings from given filename. One search string per line.
1142  *
1143  * @param filename filename of the file containing the search strings.
1144  * @param strings set of strings loaded from file. Caller needs to free this
1145  *                if number returned is greater than zero.
1146  * @param limit upper limit on the number of strings read from the file
1147  * @return number of strings found in the file. GNUNET_SYSERR on error.
1148  */
1149 static int
1150 load_search_strings (const char *filename, char ***strings, unsigned int limit)
1151 {
1152   char *data;
1153   char *buf;
1154   uint64_t filesize;
1155   unsigned int offset;
1156   int str_cnt;
1157   unsigned int i;
1158
1159   if (NULL == filename)
1160   {
1161     return GNUNET_SYSERR;
1162   }
1163
1164   if (GNUNET_YES != GNUNET_DISK_file_test (filename))
1165   {
1166     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1167                 "Could not find search strings file %s\n", filename);
1168     return GNUNET_SYSERR;
1169   }
1170   if (GNUNET_OK != GNUNET_DISK_file_size (filename, &filesize, GNUNET_YES, GNUNET_YES))
1171     filesize = 0;
1172   if (0 == filesize)
1173   {
1174     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Search strings file %s is empty.\n", filename);
1175     return GNUNET_SYSERR;
1176   }
1177   data = GNUNET_malloc (filesize);
1178   if (filesize != GNUNET_DISK_fn_read (filename, data, filesize))
1179   {
1180     GNUNET_free (data);
1181     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Could not read search strings file %s.\n",
1182          filename);
1183     return GNUNET_SYSERR;
1184   }
1185   buf = data;
1186   offset = 0;
1187   str_cnt = 0;
1188   while (offset < (filesize - 1) && str_cnt < limit)
1189   {
1190     offset++;
1191     if (((data[offset] == '\n')) && (buf != &data[offset]))
1192     {
1193       data[offset] = '\0';
1194       str_cnt++;
1195       buf = &data[offset + 1];
1196     }
1197     else if ((data[offset] == '\n') || (data[offset] == '\0'))
1198       buf = &data[offset + 1];
1199   }
1200   *strings = GNUNET_malloc (sizeof (char *) * str_cnt);
1201   offset = 0;
1202   for (i = 0; i < str_cnt; i++)
1203   {
1204     GNUNET_asprintf (&(*strings)[i], "%s%s", regex_prefix, &data[offset]);
1205     offset += strlen (&data[offset]) + 1;
1206   }
1207   GNUNET_free (data);
1208   return str_cnt;
1209 }
1210
1211
1212 /**
1213  * Main function that will be run by the scheduler.
1214  *
1215  * @param cls closure
1216  * @param args remaining command-line arguments
1217  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
1218  * @param config configuration
1219  */
1220 static void
1221 run (void *cls, char *const *args, const char *cfgfile,
1222      const struct GNUNET_CONFIGURATION_Handle *config)
1223 {
1224   unsigned int nsearchstrs;
1225
1226   if (NULL == args[0])
1227   {
1228     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1229                 _("No hosts-file specified on command line. Exiting.\n"));
1230     return;
1231   }
1232   if (NULL == args[1])
1233   {
1234     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1235                 _("No policy directory specified on command line. Exiting.\n"));
1236     return;
1237   }
1238   if (NULL == config)
1239   {
1240     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1241                 _("No configuration file given. Exiting\n"));
1242     shutdown_task = GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1243     return;
1244   }
1245
1246   if (GNUNET_OK !=
1247       GNUNET_CONFIGURATION_get_value_string (config, "REGEXPROFILER", "REGEX_PREFIX",
1248                                              &regex_prefix))
1249   {
1250     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1251                 _("Configuration option \"regex_prefix\" missing. Exiting\n"));
1252     shutdown_task = GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1253     return;
1254   }
1255
1256   if ( (NULL != data_filename) &&
1257        (NULL == (data_file =
1258                  GNUNET_DISK_file_open (data_filename,
1259                                         GNUNET_DISK_OPEN_READWRITE |
1260                                         GNUNET_DISK_OPEN_TRUNCATE |
1261                                         GNUNET_DISK_OPEN_CREATE,
1262                                         GNUNET_DISK_PERM_USER_READ |
1263                                         GNUNET_DISK_PERM_USER_WRITE))) )
1264     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
1265                               "open",
1266                               data_filename);
1267   if (GNUNET_YES != GNUNET_DISK_directory_test (args[1], GNUNET_YES))
1268   {
1269     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1270                 _("Specified policies directory does not exist. Exiting.\n"));
1271     shutdown_task = GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1272     return;
1273   }
1274   policy_dir = args[1];
1275   if (GNUNET_YES != GNUNET_DISK_file_test (args[2]))
1276   {
1277     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1278                 _("No search strings file given. Exiting.\n"));
1279     shutdown_task = GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1280     return;
1281   }
1282   nsearchstrs = load_search_strings (args[2], &search_strings, num_search_strings);
1283   if (num_search_strings != nsearchstrs)
1284   {
1285     num_search_strings = nsearchstrs;
1286     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1287                 _("Error loading search strings."
1288                   "Given file does not contain enough strings. Exiting.\n"));
1289     shutdown_task = GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1290     return;
1291   }
1292   if (0 >= num_search_strings || NULL == search_strings)
1293   {
1294     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1295                 _("Error loading search strings. Exiting.\n"));
1296     shutdown_task = GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1297     return;
1298   }
1299   cfg = GNUNET_CONFIGURATION_dup (config);
1300   if (GNUNET_OK !=
1301       GNUNET_CONFIGURATION_get_value_time (cfg, "REGEXPROFILER",
1302                                            "REANNOUNCE_PERIOD_MAX",
1303                                            &reannounce_period_max))
1304   {
1305     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
1306                 "reannounce_period_max not given. Using 10 minutes.\n");
1307     reannounce_period_max =
1308       GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 10);
1309   }
1310   unsigned int i;
1311   for (i = 0; i < num_search_strings; i++)
1312     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "search string: %s\n", search_strings[i]);
1313   abort_task =
1314       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
1315                                     (GNUNET_TIME_UNIT_SECONDS, 5), &do_abort,
1316                                     (void*) __LINE__);
1317 }
1318
1319
1320 /**
1321  * Main function.
1322  *
1323  * @param argc argument count
1324  * @param argv argument values
1325  * @return 0 on success
1326  */
1327 int
1328 main (int argc, char *const *argv)
1329 {
1330   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
1331     {'d', "details", "FILENAME",
1332      gettext_noop ("name of the file for writing statistics"),
1333      1, &GNUNET_GETOPT_set_string, &data_filename},
1334     {'n', "num-links", "COUNT",
1335       gettext_noop ("create COUNT number of random links between peers"),
1336       GNUNET_YES, &GNUNET_GETOPT_set_uint, &linking_factor },
1337     {'t', "matching-timeout", "TIMEOUT",
1338       gettext_noop ("wait TIMEOUT before considering a string match as failed"),
1339       GNUNET_YES, &GNUNET_GETOPT_set_relative_time, &search_timeout_time
1340         },
1341     {'s', "search-delay", "DELAY",
1342       gettext_noop ("wait DELAY before starting string search"),
1343       GNUNET_YES, &GNUNET_GETOPT_set_relative_time, &search_delay },
1344     {'a', "num-search-strings", "COUNT",
1345       gettext_noop ("number of search strings to read from search strings file"),
1346       GNUNET_YES, &GNUNET_GETOPT_set_uint, &num_search_strings },
1347     {'p', "max-path-compression", "MAX_PATH_COMPRESSION",
1348      gettext_noop ("maximum path compression length"),
1349      1, &GNUNET_GETOPT_set_uint, &max_path_compression},
1350     GNUNET_GETOPT_OPTION_END
1351   };
1352   int ret;
1353
1354   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
1355     return 2;
1356
1357   result = GNUNET_SYSERR;
1358   ret =
1359       GNUNET_PROGRAM_run (argc, argv,
1360                           "gnunet-regex-profiler [OPTIONS] hosts-file policy-dir search-strings-file",
1361                           _("Profiler for regex"),
1362                           options, &run, NULL);
1363
1364   if (GNUNET_OK != ret)
1365     return ret;
1366   if (GNUNET_OK != result)
1367     return 1;
1368   return 0;
1369 }