e6178eac621bae9086225693b6370ef629329371
[oweals/gnunet.git] / src / mesh / gnunet-regex-profiler.c
1 /*
2      This file is part of GNUnet.
3      (C) 2011, 2012 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 mesh/gnunet-regex-profiler.c
23  * @brief Regex profiler for testing distributed regex use.
24  * @author Bart Polot
25  * @author Max 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_mesh_service.h"
35 #include "gnunet_stream_lib.h"
36 #include "gnunet_testbed_service.h"
37
38 /**
39  * DLL of operations
40  */
41 struct DLLOperation
42 {
43   /**
44    * The testbed operation handle
45    */
46   struct GNUNET_TESTBED_Operation *op;
47
48   /**
49    * Closure
50    */
51   void *cls;
52
53   /**
54    * The next pointer for DLL
55    */
56   struct DLLOperation *next;
57
58   /**
59    * The prev pointer for DLL
60    */
61   struct DLLOperation *prev;
62 };
63
64
65 /**
66  * Available states during profiling
67  */
68 enum State
69 {
70   /**
71    * Initial state
72    */
73   STATE_INIT = 0,
74
75   /**
76    * Starting slaves
77    */
78   STATE_SLAVES_STARTING,
79
80   /**
81    * Creating peers
82    */
83   STATE_PEERS_CREATING,
84
85   /**
86    * Starting peers
87    */
88   STATE_PEERS_STARTING,
89
90   /**
91    * Linking peers
92    */
93   STATE_PEERS_LINKING,
94
95   /**
96    * Destroying peers; we can do this as the controller takes care of stopping a
97    * peer if it is running
98    */
99   STATE_PEERS_DESTROYING
100 };
101
102
103 /**
104  * An array of hosts loaded from the hostkeys file
105  */
106 static struct GNUNET_TESTBED_Host **hosts;
107
108 /**
109  * Peer handles.
110  */
111 struct RegexPeer
112 {
113   /**
114    * Peer id.
115    */
116   unsigned int id;
117
118   /**
119    * The actual testbed peer handle.
120    */
121   struct GNUNET_TESTBED_Peer *peer_handle;
122
123   /**
124    * Host on which the peer is running.
125    */
126   struct GNUNET_TESTBED_Host *host_handle;
127
128   /**
129    * Filename of the peer's policy file.
130    */
131   char *policy_file;
132
133   /**
134    * Peers search string.
135    */
136   const char *search_str;
137
138   /**
139    * Peer's mesh handle.
140    */
141   struct GNUNET_MESH_Handle *mesh_handle;
142
143   /**
144    * Peer's mesh tunnel handle.
145    */
146   struct GNUNET_MESH_Tunnel *mesh_tunnel_handle;
147
148   /**
149    * Testbed operation handle for the mesh service.
150    */
151   struct GNUNET_TESTBED_Operation *mesh_op_handle;
152
153   /**
154    * Peers's statistics handle.
155    */
156   struct GNUNET_STATISTICS_Handle *stats_handle;
157
158   /**
159    * Testbed operation handle for the statistics service.
160    */
161   struct GNUNET_TESTBED_Operation *stats_op_handle;
162
163   /**
164    * The starting time of a profiling step.
165    */
166   struct GNUNET_TIME_Absolute prof_start_time;
167 };
168
169 /**
170  * Array of peer handles used to pass to
171  * GNUNET_TESTBED_overlay_configure_topology
172  */
173 struct GNUNET_TESTBED_Peer **peer_handles;
174
175 /**
176  * The array of peers; we fill this as the peers are given to us by the testbed
177  */
178 static struct RegexPeer *peers;
179
180 /**
181  * Host registration handle
182  */
183 static struct GNUNET_TESTBED_HostRegistrationHandle *reg_handle;
184
185 /**
186  * Handle to the master controller process
187  */
188 struct GNUNET_TESTBED_ControllerProc *mc_proc;
189
190 /**
191  * Handle to the master controller
192  */
193 struct GNUNET_TESTBED_Controller *mc;
194
195 /**
196  * Handle to global configuration
197  */
198 struct GNUNET_CONFIGURATION_Handle *cfg;
199
200 /**
201  * Head of the operations list
202  */
203 struct DLLOperation *dll_op_head;
204
205 /**
206  * Tail of the operations list
207  */
208 struct DLLOperation *dll_op_tail;
209
210 /**
211  * Peer linking - topology operation
212  */
213 struct GNUNET_TESTBED_Operation *topology_op;
214
215 /**
216  * Abort task identifier
217  */
218 static GNUNET_SCHEDULER_TaskIdentifier abort_task;
219
220 /**
221  * Host registration task identifier
222  */
223 static GNUNET_SCHEDULER_TaskIdentifier register_hosts_task;
224
225 /**
226  * Global event mask for all testbed events
227  */
228 uint64_t event_mask;
229
230 /**
231  * The starting time of a profiling step
232  */
233 struct GNUNET_TIME_Absolute prof_start_time;
234
235 /**
236  * Duration profiling step has taken
237  */
238 struct GNUNET_TIME_Relative prof_time;
239
240 /**
241  * Current peer id
242  */
243 unsigned int peer_id;
244
245 /**
246  * Number of peers to be started by the profiler
247  */
248 static unsigned int num_peers;
249
250 /**
251  * Number of hosts in the hosts array
252  */
253 static unsigned int num_hosts;
254
255 /**
256  * Factor of number of links. num_links = num_peers * linking_factor.
257  */
258 static unsigned int linking_factor;
259
260 /**
261  * Number of random links to be established between peers
262  */
263 static unsigned int num_links;
264
265 /**
266  * Number of timeout failures to tolerate
267  */
268 static unsigned int num_cont_fails;
269
270 /**
271  * Number of times we try overlay connect operations
272  */
273 static unsigned int retry_links;
274
275 /**
276  * Continuous failures during overlay connect operations
277  */
278 static unsigned int cont_fails;
279
280 /**
281  * Global testing status
282  */
283 static int result;
284
285 /**
286  * current state of profiling
287  */
288 enum State state;
289
290 /**
291  * Folder where policy files are stored.
292  */
293 static char * policy_dir;
294
295 /**
296  * Search strings.
297  */
298 static char **search_strings;
299
300 /**
301  * Number of search strings.
302  */
303 static int num_search_strings;
304
305 /**
306  * Number of peers found with search strings.
307  */
308 static unsigned int peers_found;
309
310 /**
311  * Search task identifier
312  */
313 static GNUNET_SCHEDULER_TaskIdentifier search_task;
314
315 /**
316  * Search timeout task identifier.
317  */
318 static GNUNET_SCHEDULER_TaskIdentifier search_timeout_task;
319
320 /**
321  * Search timeout in seconds.
322  */
323 static struct GNUNET_TIME_Relative search_timeout = { 60000 };
324
325 /**
326  * How long do we wait before starting the search?
327  * Default: 1 m.
328  */
329 static struct GNUNET_TIME_Relative search_delay = { 60000 };
330
331 /**
332  * File to log statistics to.
333  */
334 static struct GNUNET_DISK_FileHandle *data_file;
335
336 /**
337  * Filename to log statistics to.
338  */
339 static char *data_filename;
340
341
342 /******************************************************************************/
343 /******************************  DECLARATIONS  ********************************/
344 /******************************************************************************/
345
346
347 /**
348  * Method called whenever a peer has connected to the tunnel.
349  *
350  * @param cls closure
351  * @param peer_id peer identity the tunnel was created to, NULL on timeout
352  * @param atsi performance data for the connection
353  *
354  */
355 void
356 mesh_peer_connect_handler (void *cls,
357                            const struct GNUNET_PeerIdentity* peer_id,
358                            const struct GNUNET_ATS_Information * atsi);
359
360
361 /**
362  * Method called whenever a peer has disconnected from the tunnel.
363  * Implementations of this callback must NOT call
364  * GNUNET_MESH_tunnel_destroy immediately, but instead schedule those
365  * to run in some other task later.  However, calling
366  * "GNUNET_MESH_notify_transmit_ready_cancel" is allowed.
367  *
368  * @param cls closure
369  * @param peer_id peer identity the tunnel stopped working with
370  */
371 void
372 mesh_peer_disconnect_handler (void *cls,
373                               const struct GNUNET_PeerIdentity * peer_id);
374
375
376 /******************************************************************************/
377 /********************************  SHUTDOWN  **********************************/
378 /******************************************************************************/
379
380
381 /**
382  * Shutdown nicely
383  *
384  * @param cls NULL
385  * @param tc the task context
386  */
387 static void
388 do_shutdown (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
389 {
390   struct DLLOperation *dll_op;
391   unsigned int nhost;
392   unsigned int peer_cnt;
393   unsigned int search_str_cnt;
394
395   for (peer_cnt = 0; peer_cnt < num_peers; peer_cnt++)
396   {
397     if (NULL != peers[peer_cnt].mesh_op_handle)
398       GNUNET_TESTBED_operation_cancel (peers[peer_cnt].mesh_op_handle);
399     if (NULL != peers[peer_cnt].stats_op_handle)
400       GNUNET_TESTBED_operation_cancel (peers[peer_cnt].stats_op_handle);
401   }
402   for (search_str_cnt = 0; search_str_cnt < num_search_strings; search_str_cnt++)
403   {
404     GNUNET_free (search_strings[search_str_cnt]);
405   }
406   GNUNET_free (search_strings);
407   if (GNUNET_SCHEDULER_NO_TASK != abort_task)
408     GNUNET_SCHEDULER_cancel (abort_task);
409   if (GNUNET_SCHEDULER_NO_TASK != register_hosts_task)
410     GNUNET_SCHEDULER_cancel (register_hosts_task);
411   if (NULL != reg_handle)
412     GNUNET_TESTBED_cancel_registration (reg_handle);
413   if (NULL != topology_op)
414     GNUNET_TESTBED_operation_cancel (topology_op);
415   for (nhost = 0; nhost < num_hosts; nhost++)
416     if (NULL != hosts[nhost])
417       GNUNET_TESTBED_host_destroy (hosts[nhost]);
418   GNUNET_free_non_null (hosts);
419   while (NULL != (dll_op = dll_op_head))
420   {
421     GNUNET_TESTBED_operation_cancel (dll_op->op);
422     GNUNET_CONTAINER_DLL_remove (dll_op_head, dll_op_tail, dll_op);
423     GNUNET_free (dll_op);
424   }
425   if (NULL != mc)
426     GNUNET_TESTBED_controller_disconnect (mc);
427   if (NULL != mc_proc)
428     GNUNET_TESTBED_controller_stop (mc_proc);
429   if (NULL != cfg)
430     GNUNET_CONFIGURATION_destroy (cfg);
431   if (NULL != data_file)
432     GNUNET_DISK_file_close (data_file);
433
434   GNUNET_SCHEDULER_shutdown (); /* Stop scheduler to shutdown testbed run */
435 }
436
437
438 /**
439  * abort task to run on test timed out
440  *
441  * @param cls NULL
442  * @param tc the task context
443  */
444 static void
445 do_abort (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
446 {
447   GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Aborting\n");
448   abort_task = GNUNET_SCHEDULER_NO_TASK;
449   result = GNUNET_SYSERR;
450   GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
451 }
452
453
454 /******************************************************************************/
455 /*********************  STATISTICS SERVICE CONNECTIONS  ***********************/
456 /******************************************************************************/
457
458 /**
459  * Adapter function called to establish a connection to
460  * statistics service.
461  *
462  * @param cls closure
463  * @param cfg configuration of the peer to connect to; will be available until
464  *          GNUNET_TESTBED_operation_done() is called on the operation returned
465  *          from GNUNET_TESTBED_service_connect()
466  * @return service handle to return in 'op_result', NULL on error
467  */
468 static void *
469 stats_ca (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg)
470 {
471   return GNUNET_STATISTICS_create ("<driver>", cfg);
472 }
473
474
475 /**
476  * Adapter function called to destroy a connection to
477  * statistics service.
478  *
479  * @param cls closure
480  * @param op_result service handle returned from the connect adapter
481  */
482 static void
483 stats_da (void *cls, void *op_result)
484 {
485   GNUNET_STATISTICS_destroy (op_result, GNUNET_NO);
486 }
487
488
489 /**
490  * Process statistic values.
491  *
492  * @param cls closure
493  * @param subsystem name of subsystem that created the statistic
494  * @param name the name of the datum
495  * @param value the current value
496  * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
497  * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
498  */
499 static int
500 stats_iterator (void *cls, const char *subsystem, const char *name,
501                 uint64_t value, int is_persistent)
502 {
503   struct RegexPeer *peer = cls;
504   char output_buffer[512];
505   size_t size;
506
507   if (NULL == data_file)
508   {
509     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
510                 "%p -> %s [%s]: %llu\n",
511                 peer, subsystem, name, value);
512     return GNUNET_OK;
513   }
514   size =
515     GNUNET_snprintf (output_buffer,
516                      sizeof (output_buffer),
517                      "%p [%s] %llu %s\n",
518                      peer,
519                      subsystem, value, name);
520   if (size != GNUNET_DISK_file_write (data_file, output_buffer, size))
521     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Unable to write to file!\n");
522
523   return GNUNET_OK;
524 }
525
526
527 /**
528  * Stats callback.
529  *
530  * @param cls closure
531  * @param success GNUNET_OK if statistics were
532  *        successfully obtained, GNUNET_SYSERR if not.
533  */
534 static void
535 stats_cb (void *cls,
536           int success)
537 {
538   static unsigned int peer_cnt;
539   struct RegexPeer *peer = cls;
540
541   if (GNUNET_OK != success)
542   {
543     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
544                 "Getting statistics for peer %u failed!\n",
545                 peer->id);
546     return;
547   }
548
549   GNUNET_TESTBED_operation_done (peer->stats_op_handle);
550   peer->stats_op_handle = NULL;
551
552   if (++peer_cnt == num_search_strings)
553   {
554     GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
555   }
556 }
557
558
559 /**
560  * Function called by testbed once we are connected to stats service.
561  *
562  * @param cls the 'struct RegexPeer' for which we connected to stats
563  * @param op connect operation handle
564  * @param ca_result handle to stats service
565  * @param emsg error message on failure
566  */
567 static void
568 stats_connect_cb (void *cls,
569                   struct GNUNET_TESTBED_Operation *op,
570                   void *ca_result,
571                   const char *emsg)
572 {
573   struct RegexPeer *peer = cls;
574
575   if (NULL == ca_result)
576   {
577     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
578                 "Failed to connect to statistics service on peer %u: %s\n",
579                 peer->id, emsg);
580     return;
581   }
582
583   peer->stats_handle = ca_result;
584
585   peer->mesh_tunnel_handle = GNUNET_MESH_tunnel_create (peer->mesh_handle,
586                                                         NULL,
587                                                         &mesh_peer_connect_handler,
588                                                         &mesh_peer_disconnect_handler,
589                                                         peer);
590
591   peer->prof_start_time = GNUNET_TIME_absolute_get ();
592
593   GNUNET_MESH_peer_request_connect_by_string (peer->mesh_tunnel_handle,
594                                               peer->search_str);
595 }
596
597
598 /******************************************************************************/
599 /************************  MESH SERVICE CONNECTIONS  **************************/
600 /******************************************************************************/
601
602 /**
603  * Method called whenever another peer has added us to a tunnel
604  * the other peer initiated.
605  * Only called (once) upon reception of data with a message type which was
606  * subscribed to in GNUNET_MESH_connect. A call to GNUNET_MESH_tunnel_destroy
607  * causes te tunnel to be ignored and no further notifications are sent about
608  * the same tunnel.
609  *
610  * @param cls closure
611  * @param tunnel new handle to the tunnel
612  * @param initiator peer that started the tunnel
613  * @param atsi performance information for the tunnel
614  * @return initial tunnel context for the tunnel
615  *         (can be NULL -- that's not an error)
616  */
617 void *
618 mesh_inbound_tunnel_handler (void *cls, struct GNUNET_MESH_Tunnel *tunnel,
619                              const struct GNUNET_PeerIdentity *initiator,
620                              const struct GNUNET_ATS_Information *atsi)
621 {
622   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh inbound tunnel handler.\n");
623
624   return NULL;
625 }
626
627
628 /**
629  * Function called whenever an inbound tunnel is destroyed.  Should clean up
630  * any associated state.  This function is NOT called if the client has
631  * explicitly asked for the tunnel to be destroyed using
632  * GNUNET_MESH_tunnel_destroy. It must NOT call GNUNET_MESH_tunnel_destroy on
633  * the tunnel.
634  *
635  * @param cls closure (set from GNUNET_MESH_connect)
636  * @param tunnel connection to the other end (henceforth invalid)
637  * @param tunnel_ctx place where local state associated
638  *                   with the tunnel is stored
639  */
640 void
641 mesh_tunnel_end_handler (void *cls, const struct GNUNET_MESH_Tunnel *tunnel,
642                          void *tunnel_ctx)
643 {
644   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh tunnel end handler.\n");
645 }
646
647
648 /**
649  * Method called whenever a peer has disconnected from the tunnel.
650  * Implementations of this callback must NOT call
651  * GNUNET_MESH_tunnel_destroy immediately, but instead schedule those
652  * to run in some other task later.  However, calling
653  * "GNUNET_MESH_notify_transmit_ready_cancel" is allowed.
654  *
655  * @param cls closure
656  * @param peer_id peer identity the tunnel stopped working with
657  */
658 void
659 mesh_peer_disconnect_handler (void *cls,
660                               const struct GNUNET_PeerIdentity * peer_id)
661 {
662   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh peer disconnect handler.\n");
663 }
664
665
666 /**
667  * Method called whenever a peer has connected to the tunnel.
668  *
669  * @param cls closure
670  * @param peer_id peer identity the tunnel was created to, NULL on timeout
671  * @param atsi performance data for the connection
672  *
673  */
674 void
675 mesh_peer_connect_handler (void *cls,
676                            const struct GNUNET_PeerIdentity* peer_id,
677                            const struct GNUNET_ATS_Information * atsi)
678 {
679   struct RegexPeer *peer = cls;
680   char output_buffer[512];
681   size_t size;
682
683   peers_found++;
684
685   if (NULL == peer_id)
686   {
687     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
688                 "String matching timed out for string %s on peer %u (%i/%i)\n",
689                 peer->search_str, peer->id, peers_found, num_search_strings);
690   }
691   else
692   {
693     prof_time = GNUNET_TIME_absolute_get_duration (peer->prof_start_time);
694     GNUNET_log (GNUNET_ERROR_TYPE_INFO, 
695                 "String %s successfully matched on peer %u after %s (%i/%i)\n",
696                 peer->search_str, peer->id, GNUNET_STRINGS_relative_time_to_string (prof_time, GNUNET_NO), 
697                 peers_found, num_search_strings);
698
699     if (NULL != data_file)
700     {
701       size =
702         GNUNET_snprintf (output_buffer,
703                          sizeof (output_buffer),
704                          "Peer: %u (%p)\nHost: %s\nPolicy file: %s\nSearch string: %s\nSearch duration: %s\n\n",
705                          peer->id,
706                          peer,
707                          GNUNET_TESTBED_host_get_hostname (peer->host_handle),
708                          peer->policy_file,
709                          peer->search_str,
710                          GNUNET_STRINGS_relative_time_to_string (prof_time, GNUNET_NO));
711
712       if (size != GNUNET_DISK_file_write (data_file, output_buffer, size))
713         GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Unable to write to file!\n");
714     }
715
716     if (NULL == GNUNET_STATISTICS_get (peer->stats_handle, "mesh", NULL,
717                                        GNUNET_TIME_UNIT_FOREVER_REL,
718                                        NULL,
719                                        &stats_iterator, peer))
720     {
721       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
722                   "Could not get mesh statistics of peer %u!\n", peer->id);
723     }
724     if (NULL == GNUNET_STATISTICS_get (peer->stats_handle, "transport", NULL,
725                                        GNUNET_TIME_UNIT_FOREVER_REL,
726                                        NULL,
727                                        &stats_iterator, peer))
728     {
729       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
730                   "Could not get transport statistics of peer %u!\n", peer->id);
731     }
732     if (NULL == GNUNET_STATISTICS_get (peer->stats_handle, "dht", NULL,
733                                        GNUNET_TIME_UNIT_FOREVER_REL,
734                                        &stats_cb,
735                                        &stats_iterator, peer))
736     {
737       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
738                   "Could not get dht statistics of peer %u!\n", peer->id);
739     }
740   }
741
742   if (peers_found == num_search_strings)
743   {
744     prof_time = GNUNET_TIME_absolute_get_duration (prof_start_time);
745     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
746                 "All strings successfully matched in %s\n", 
747                 GNUNET_STRINGS_relative_time_to_string (prof_time, GNUNET_NO));
748     printf ("All strings successfully matched. Shutting down.\n");
749     fflush (stdout);
750
751     if (GNUNET_SCHEDULER_NO_TASK != search_timeout_task)
752       GNUNET_SCHEDULER_cancel (search_timeout_task);
753   }
754 }
755
756
757 /**
758  * Connect by string timeout task
759  *
760  * @param cls NULL
761  * @param tc the task context
762  */
763 static void
764 do_connect_by_string_timeout (void *cls,
765                               const struct GNUNET_SCHEDULER_TaskContext * tc)
766 {
767   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
768               "Finding matches to all strings did not succeed after %s.\n",
769               GNUNET_STRINGS_relative_time_to_string (search_timeout, GNUNET_NO));
770   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
771               "Found %i of %i strings\n", peers_found, num_search_strings);
772
773   GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
774 }
775
776
777 /**
778  * Connect by string task that is run to search for a string in the NFA
779  *
780  * @param cls NULL
781  * @param tc the task context
782  */
783 static void
784 do_connect_by_string (void *cls,
785                       const struct GNUNET_SCHEDULER_TaskContext * tc)
786 {
787   unsigned int search_cnt;
788   struct RegexPeer *peer;
789
790   for (search_cnt = 0; search_cnt < num_search_strings; search_cnt++)
791   {
792     peer = &peers[search_cnt % num_peers];
793     peer->search_str = search_strings[search_cnt];
794
795     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
796                 "Searching for string \"%s\" on peer %d with file %s\n",
797                 peer->search_str, (search_cnt % num_peers), peer->policy_file);
798
799     /* First connect to stats service, then try connecting by string in stats_connect_cb */
800     peer->stats_op_handle =
801       GNUNET_TESTBED_service_connect (NULL,
802                                       peers->peer_handle,
803                                       "statistics",
804                                       &stats_connect_cb,
805                                       peer,
806                                       &stats_ca,
807                                       &stats_da,
808                                       peer);
809   }
810
811   search_timeout_task = GNUNET_SCHEDULER_add_delayed (search_timeout,
812                                                       &do_connect_by_string_timeout, NULL);
813 }
814
815
816 /**
817  * Mesh connect callback.
818  *
819  * @param cls internal peer id.
820  * @param op operation handle.
821  * @param ca_result connect adapter result.
822  * @param emsg error message.
823  */
824 void
825 mesh_connect_cb (void *cls, struct GNUNET_TESTBED_Operation *op,
826                  void *ca_result, const char *emsg)
827 {
828   static unsigned int connected_mesh_handles;
829   struct RegexPeer *peer = (struct RegexPeer *) cls;
830   char *regex;
831   char *data;
832   char *buf;
833   uint64_t filesize;
834   unsigned int offset;
835
836   if (NULL != emsg)
837   {
838     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Mesh connect failed: %s\n", emsg);
839     GNUNET_assert (0);
840   }
841
842   GNUNET_assert (peer->mesh_op_handle == op);
843   GNUNET_assert (peer->mesh_handle == ca_result);
844   GNUNET_assert (NULL != peer->policy_file);
845
846   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
847               "Announcing regexes for peer %u with file %s\n", 
848               peer->id, peer->policy_file);
849
850   if (GNUNET_YES != GNUNET_DISK_file_test (peer->policy_file))
851   {
852     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
853                 "Could not find policy file %s\n", peer->policy_file);
854     return;
855   }
856   if (GNUNET_OK != GNUNET_DISK_file_size (peer->policy_file, &filesize, GNUNET_YES, GNUNET_YES))
857     filesize = 0;
858   if (0 == filesize)
859   {
860     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Policy file %s is empty.\n", peer->policy_file);
861     return;
862   }
863   data = GNUNET_malloc (filesize);
864   if (filesize != GNUNET_DISK_fn_read (peer->policy_file, data, filesize))
865   {
866     GNUNET_free (data);
867     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Could not read policy file %s.\n",
868          peer->policy_file);
869     return;
870   }
871   buf = data;
872   offset = 0;
873   regex = NULL;
874   while (offset < (filesize - 1))
875   {
876     offset++;
877     if (((data[offset] == '\n')) && (buf != &data[offset]))
878     {
879       data[offset] = '\0';
880       regex = buf;
881       GNUNET_assert (NULL != regex);
882       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Announcing regex: %s on peer %u \n", 
883                   regex, peer->id);
884       GNUNET_MESH_announce_regex (peer->mesh_handle, regex);
885       buf = &data[offset + 1];
886     }
887     else if ((data[offset] == '\n') || (data[offset] == '\0'))
888       buf = &data[offset + 1];
889   }
890   GNUNET_free (data);
891
892   if (++connected_mesh_handles == num_peers)
893   {
894     printf ("\nWaiting %s before starting to search.\n",
895             GNUNET_STRINGS_relative_time_to_string (search_delay, GNUNET_YES));
896     fflush (stdout);
897
898     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
899                 "All mesh handles connected. Waiting %s before starting to search.\n",
900                 GNUNET_STRINGS_relative_time_to_string (search_delay, GNUNET_YES));
901
902     search_task = GNUNET_SCHEDULER_add_delayed (search_delay,
903                                                 &do_connect_by_string, NULL);
904   }
905 }
906
907
908 /**
909  * Mesh connect adapter.
910  *
911  * @param cls not used.
912  * @param cfg configuration handle.
913  *
914  * @return
915  */
916 void *
917 mesh_ca (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg)
918 {
919   GNUNET_MESH_ApplicationType app;
920   struct RegexPeer *peer = cls;
921
922   static struct GNUNET_MESH_MessageHandler handlers[] = {
923     {NULL, 0, 0}
924   };
925
926   app = (GNUNET_MESH_ApplicationType)0;
927
928   peer->mesh_handle =
929     GNUNET_MESH_connect (cfg, cls, NULL, NULL, handlers, &app);
930
931   return peer->mesh_handle;
932 }
933
934
935 /**
936  * Adapter function called to destroy a connection to
937  * the mesh service
938  *
939  * @param cls closure
940  * @param op_result service handle returned from the connect adapter
941  */
942 void
943 mesh_da (void *cls, void *op_result)
944 {
945   struct RegexPeer *peer = (struct RegexPeer *) cls;
946
947   GNUNET_assert (peer->mesh_handle == op_result);
948
949   if (NULL != peer->mesh_tunnel_handle)
950   {
951     GNUNET_MESH_tunnel_destroy (peer->mesh_tunnel_handle);
952     peer->mesh_tunnel_handle = NULL;
953   }
954
955   if (NULL != peer->mesh_handle)
956   {
957     GNUNET_MESH_disconnect (peer->mesh_handle);
958     peer->mesh_handle = NULL;
959   }
960 }
961
962
963 /******************************************************************************/
964 /***************************  TESTBED PEER SETUP  *****************************/
965 /******************************************************************************/
966
967
968 /**
969  * Functions of this signature are called when a peer has been successfully
970  * started or stopped.
971  *
972  * @param cls the closure from GNUNET_TESTBED_peer_start/stop()
973  * @param emsg NULL on success; otherwise an error description
974  */
975 static void
976 peer_churn_cb (void *cls, const char *emsg)
977 {
978   struct DLLOperation *dll_op = cls;
979   struct GNUNET_TESTBED_Operation *op;
980   static unsigned int started_peers;
981   unsigned int peer_cnt;
982
983   op = dll_op->op;
984   GNUNET_CONTAINER_DLL_remove (dll_op_head, dll_op_tail, dll_op);
985   GNUNET_free (dll_op);
986   if (NULL != emsg)
987   {
988     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
989          _("An operation has failed while starting peers\n"));
990     GNUNET_TESTBED_operation_done (op);
991     if (GNUNET_SCHEDULER_NO_TASK != abort_task)
992       GNUNET_SCHEDULER_cancel (abort_task);
993     abort_task = GNUNET_SCHEDULER_add_now (&do_abort, NULL);
994     return;
995   }
996   GNUNET_TESTBED_operation_done (op);
997   if (++started_peers == num_peers)
998   {
999     prof_time = GNUNET_TIME_absolute_get_duration (prof_start_time);
1000     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1001                 "All peers started successfully in %s\n",
1002                 GNUNET_STRINGS_relative_time_to_string (prof_time, GNUNET_NO));
1003     result = GNUNET_OK;
1004
1005     peer_handles = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_Peer *) * num_peers);
1006     for (peer_cnt = 0; peer_cnt < num_peers; peer_cnt++)
1007       peer_handles[peer_cnt] = peers[peer_cnt].peer_handle;
1008
1009     if (0 == linking_factor)
1010       linking_factor = 1;
1011     num_links = linking_factor * num_peers;
1012
1013     state = STATE_PEERS_LINKING;
1014     /* Do overlay connect */
1015     prof_start_time = GNUNET_TIME_absolute_get ();
1016     topology_op =
1017         GNUNET_TESTBED_overlay_configure_topology (NULL, num_peers, peer_handles,
1018                                                    GNUNET_TESTBED_TOPOLOGY_ERDOS_RENYI,
1019                                                    num_links,
1020                                                    GNUNET_TESTBED_TOPOLOGY_DISABLE_AUTO_RETRY,
1021                                                    GNUNET_TESTBED_TOPOLOGY_OPTION_END);
1022     if (NULL == topology_op)
1023     {
1024       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1025                   "Cannot create topology, op handle was NULL\n");
1026       GNUNET_assert (0);
1027     }
1028   }
1029 }
1030
1031
1032 /**
1033  * Functions of this signature are called when a peer has been successfully
1034  * created
1035  *
1036  * @param cls the closure from GNUNET_TESTBED_peer_create()
1037  * @param peer the handle for the created peer; NULL on any error during
1038  *          creation
1039  * @param emsg NULL if peer is not NULL; else MAY contain the error description
1040  */
1041 static void
1042 peer_create_cb (void *cls, struct GNUNET_TESTBED_Peer *peer, const char *emsg)
1043 {
1044   struct DLLOperation *dll_op = cls;
1045   struct RegexPeer *peer_ptr;
1046   static unsigned int created_peers;
1047   unsigned int peer_cnt;
1048
1049   if (NULL != emsg)
1050   {
1051     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1052          _("Creating a peer failed. Error: %s\n"), emsg);
1053     GNUNET_TESTBED_operation_done (dll_op->op);
1054     GNUNET_CONTAINER_DLL_remove (dll_op_head, dll_op_tail, dll_op);
1055     GNUNET_free (dll_op);
1056     if (GNUNET_SCHEDULER_NO_TASK != abort_task)
1057       GNUNET_SCHEDULER_cancel (abort_task);
1058     abort_task = GNUNET_SCHEDULER_add_now (&do_abort, NULL);
1059     return;
1060   }
1061
1062   peer_ptr = dll_op->cls;
1063   GNUNET_assert (NULL == peer_ptr->peer_handle);
1064   peer_ptr->peer_handle = peer;
1065   GNUNET_TESTBED_operation_done (dll_op->op);
1066   GNUNET_CONTAINER_DLL_remove (dll_op_head, dll_op_tail, dll_op);
1067   GNUNET_free (dll_op);
1068
1069   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Peer %i created on host %s\n",
1070               peer_ptr->id,
1071               GNUNET_TESTBED_host_get_hostname (peer_ptr->host_handle));
1072
1073   if (++created_peers == num_peers)
1074   {
1075     prof_time = GNUNET_TIME_absolute_get_duration (prof_start_time);
1076     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1077                 "All peers created successfully in %s\n",
1078                 GNUNET_STRINGS_relative_time_to_string (prof_time, GNUNET_NO));
1079     /* Now peers are to be started */
1080     state = STATE_PEERS_STARTING;
1081     prof_start_time = GNUNET_TIME_absolute_get ();
1082     for (peer_cnt = 0; peer_cnt < num_peers; peer_cnt++)
1083     {
1084       dll_op = GNUNET_malloc (sizeof (struct DLLOperation));
1085       dll_op->op = GNUNET_TESTBED_peer_start (dll_op, peers[peer_cnt].peer_handle,
1086                                               &peer_churn_cb, dll_op);
1087       GNUNET_CONTAINER_DLL_insert_tail (dll_op_head, dll_op_tail, dll_op);
1088     }
1089   }
1090 }
1091
1092 /**
1093  * Function called with a filename.
1094  *
1095  * @param cls closure
1096  * @param filename complete filename (absolute path)
1097  * @return GNUNET_OK to continue to iterate,
1098  *  GNUNET_SYSERR to abort iteration with error!
1099  */
1100 int
1101 policy_filename_cb (void *cls, const char *filename)
1102 {
1103   static unsigned int peer_cnt;
1104   struct DLLOperation *dll_op;
1105   struct RegexPeer *peer = &peers[peer_cnt];
1106
1107   GNUNET_assert (NULL != peer);
1108
1109   peer->id = peer_cnt;
1110   peer->policy_file = GNUNET_strdup (filename);
1111   /* Do not start peers on hosts[0] (master controller) */
1112   peer->host_handle = hosts[1 + (peer_cnt % (num_hosts -1))];
1113   peer->mesh_handle = NULL;
1114   peer->mesh_tunnel_handle = NULL;
1115   peer->stats_handle = NULL;
1116   peer->stats_op_handle = NULL;
1117
1118   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Creating peer %i on host %s for policy file %s\n",
1119               peer->id,
1120               GNUNET_TESTBED_host_get_hostname (peer->host_handle),
1121               filename);
1122
1123   dll_op = GNUNET_malloc (sizeof (struct DLLOperation));
1124   dll_op->cls = &peers[peer_cnt];
1125   dll_op->op = GNUNET_TESTBED_peer_create (mc,
1126                                            peer->host_handle,
1127                                            cfg,
1128                                            &peer_create_cb,
1129                                            dll_op);
1130   GNUNET_CONTAINER_DLL_insert_tail (dll_op_head, dll_op_tail, dll_op);
1131   peer_cnt++;
1132
1133   return GNUNET_OK;
1134 }
1135
1136
1137 /**
1138  * Controller event callback.
1139  *
1140  * @param cls NULL
1141  * @param event the controller event
1142  */
1143 static void
1144 controller_event_cb (void *cls,
1145                      const struct GNUNET_TESTBED_EventInformation *event)
1146 {
1147   struct DLLOperation *dll_op;
1148   struct GNUNET_TESTBED_Operation *op;
1149
1150   switch (state)
1151   {
1152   case STATE_SLAVES_STARTING:
1153     switch (event->type)
1154     {
1155     case GNUNET_TESTBED_ET_OPERATION_FINISHED:
1156       {
1157         static unsigned int slaves_started;
1158
1159         dll_op = event->details.operation_finished.op_cls;
1160         GNUNET_CONTAINER_DLL_remove (dll_op_head, dll_op_tail, dll_op);
1161         GNUNET_free (dll_op);
1162         op = event->details.operation_finished.operation;
1163         if (NULL != event->details.operation_finished.emsg)
1164         {
1165           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1166                _("An operation has failed while starting slaves\n"));
1167           GNUNET_TESTBED_operation_done (op);
1168           if (GNUNET_SCHEDULER_NO_TASK != abort_task)
1169             GNUNET_SCHEDULER_cancel (abort_task);
1170           abort_task = GNUNET_SCHEDULER_add_now (&do_abort, NULL);
1171           return;
1172         }
1173         GNUNET_TESTBED_operation_done (op);
1174         /* Proceed to start peers */
1175         if (++slaves_started == num_hosts - 1)
1176         {
1177           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1178                       "All slaves started successfully\n");
1179
1180           state = STATE_PEERS_CREATING;
1181           prof_start_time = GNUNET_TIME_absolute_get ();
1182
1183           num_peers = GNUNET_DISK_directory_scan (policy_dir,
1184                                                   NULL,
1185                                                   NULL);
1186           peers = GNUNET_malloc (sizeof (struct RegexPeer) * num_peers);
1187
1188           GNUNET_DISK_directory_scan (policy_dir,
1189                                       &policy_filename_cb,
1190                                       NULL);
1191         }
1192       }
1193       break;
1194     default:
1195       GNUNET_assert (0);
1196     }
1197     break;
1198   case STATE_PEERS_STARTING:
1199     switch (event->type)
1200     {
1201     case GNUNET_TESTBED_ET_OPERATION_FINISHED:
1202       /* Control reaches here when peer start fails */
1203     case GNUNET_TESTBED_ET_PEER_START:
1204       /* we handle peer starts in peer_churn_cb */
1205       break;
1206     default:
1207       GNUNET_assert (0);
1208     }
1209     break;
1210   case STATE_PEERS_LINKING:
1211    switch (event->type)
1212     {
1213       static unsigned int established_links;
1214     case GNUNET_TESTBED_ET_OPERATION_FINISHED:
1215       /* Control reaches here when a peer linking operation fails */
1216       if (NULL != event->details.operation_finished.emsg)
1217       {
1218         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1219              _("An operation has failed while linking\n"));
1220         printf ("F");
1221         fflush (stdout);
1222         retry_links++;
1223
1224         if (++cont_fails > num_cont_fails)
1225         {
1226           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1227                       "We have a very high peer linking failure rate: %u (threshold: %u)\n",
1228                       cont_fails,
1229                       num_cont_fails);
1230         }
1231       }
1232       /* We do no retries, consider this link as established */
1233       /* break; */
1234     case GNUNET_TESTBED_ET_CONNECT:
1235       {
1236         unsigned int peer_cnt;
1237         char output_buffer[512];
1238         size_t size;
1239
1240         if (0 == established_links)
1241           printf ("Establishing links .");
1242         else
1243         {
1244           printf (".");
1245           fflush (stdout);
1246         }
1247         if (++established_links == num_links)
1248         {
1249           fflush (stdout);
1250           prof_time = GNUNET_TIME_absolute_get_duration (prof_start_time);
1251           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1252                       "%u links established in %s\n",
1253                       num_links, 
1254                       GNUNET_STRINGS_relative_time_to_string (prof_time, GNUNET_NO));
1255           result = GNUNET_OK;
1256           GNUNET_free (peer_handles);
1257
1258           if (NULL != data_file)
1259           {
1260             size =
1261               GNUNET_snprintf (output_buffer,
1262                                sizeof (output_buffer),
1263                                "# of peers: %u\n# of links established: %u\nTime to establish links: %s\nLinking failures: %u\n\n",
1264                                num_peers,
1265                                (established_links - cont_fails),
1266                                GNUNET_STRINGS_relative_time_to_string (prof_time, GNUNET_NO),
1267                                cont_fails);
1268             
1269             if (size != GNUNET_DISK_file_write (data_file, output_buffer, size))
1270               GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Unable to write to file!\n");
1271           }
1272           
1273           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1274                       "Connecting to mesh and statistics service...\n");
1275           for (peer_cnt = 0; peer_cnt < num_peers; peer_cnt++)
1276           {
1277             peers[peer_cnt].mesh_op_handle =
1278               GNUNET_TESTBED_service_connect (NULL,
1279                                               peers[peer_cnt].peer_handle,
1280                                               "mesh",
1281                                               &mesh_connect_cb,
1282                                               &peers[peer_cnt],
1283                                               &mesh_ca,
1284                                               &mesh_da,
1285                                               &peers[peer_cnt]);
1286           }
1287         }
1288       }
1289       break;
1290     default:
1291       GNUNET_assert (0);
1292     }
1293     break;
1294   default:
1295     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
1296                 "Unexpected controller_cb with state %i!\n", state);
1297     GNUNET_assert (0);
1298   }
1299 }
1300
1301
1302 /**
1303  * Task to register all hosts available in the global host list
1304  *
1305  * @param cls NULL
1306  * @param tc the scheduler task context
1307  */
1308 static void
1309 register_hosts (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1310
1311
1312 /**
1313  * Callback which will be called to after a host registration succeeded or failed
1314  *
1315  * @param cls the closure
1316  * @param emsg the error message; NULL if host registration is successful
1317  */
1318 static void
1319 host_registration_completion (void *cls, const char *emsg)
1320 {
1321   reg_handle = NULL;
1322   if (NULL != emsg)
1323   {
1324     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1325                 _("Host registration failed for a host. Error: %s\n"), emsg);
1326     if (GNUNET_SCHEDULER_NO_TASK != abort_task)
1327       GNUNET_SCHEDULER_cancel (abort_task);
1328     abort_task = GNUNET_SCHEDULER_add_now (&do_abort, NULL);
1329     return;
1330   }
1331   register_hosts_task = GNUNET_SCHEDULER_add_now (&register_hosts, NULL);
1332 }
1333
1334
1335 /**
1336  * Task to register all hosts available in the global host list
1337  *
1338  * @param cls NULL
1339  * @param tc the scheduler task context
1340  */
1341 static void
1342 register_hosts (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1343 {
1344   struct DLLOperation *dll_op;
1345   static unsigned int reg_host;
1346   unsigned int slave;
1347
1348   register_hosts_task = GNUNET_SCHEDULER_NO_TASK;
1349   if (reg_host == num_hosts - 1)
1350   {
1351     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1352                 "All hosts successfully registered\n");
1353     /* Start slaves */
1354     state = STATE_SLAVES_STARTING;
1355     for (slave = 1; slave < num_hosts; slave++)
1356     {
1357       dll_op = GNUNET_malloc (sizeof (struct DLLOperation));
1358       dll_op->op = GNUNET_TESTBED_controller_link (dll_op,
1359                                                    mc,
1360                                                    hosts[slave],
1361                                                    hosts[0],
1362                                                    cfg,
1363                                                    GNUNET_YES);
1364       GNUNET_CONTAINER_DLL_insert_tail (dll_op_head, dll_op_tail, dll_op);
1365     }
1366     return;
1367   }
1368   reg_handle = GNUNET_TESTBED_register_host (mc, hosts[++reg_host],
1369                                              host_registration_completion,
1370                                              NULL);
1371 }
1372
1373
1374 /**
1375  * Callback to signal successfull startup of the controller process
1376  *
1377  * @param cls the closure from GNUNET_TESTBED_controller_start()
1378  * @param config the configuration with which the controller has been started;
1379  *          NULL if status is not GNUNET_OK
1380  * @param status GNUNET_OK if the startup is successfull; GNUNET_SYSERR if not,
1381  *          GNUNET_TESTBED_controller_stop() shouldn't be called in this case
1382  */
1383 static void
1384 status_cb (void *cls, const struct GNUNET_CONFIGURATION_Handle *config, int status)
1385 {
1386   if (GNUNET_SCHEDULER_NO_TASK != abort_task)
1387     GNUNET_SCHEDULER_cancel (abort_task);
1388   if (GNUNET_OK != status)
1389   {
1390     mc_proc = NULL;
1391     abort_task = GNUNET_SCHEDULER_add_now (&do_abort, NULL);
1392     return;
1393   }
1394   event_mask = 0;
1395   event_mask |= (1LL << GNUNET_TESTBED_ET_PEER_START);
1396   event_mask |= (1LL << GNUNET_TESTBED_ET_PEER_STOP);
1397   event_mask |= (1LL << GNUNET_TESTBED_ET_CONNECT);
1398   event_mask |= (1LL << GNUNET_TESTBED_ET_DISCONNECT);
1399   event_mask |= (1LL << GNUNET_TESTBED_ET_OPERATION_FINISHED);
1400   mc = GNUNET_TESTBED_controller_connect (config, hosts[0], event_mask,
1401                                           &controller_event_cb, NULL);
1402   if (NULL == mc)
1403   {
1404     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1405                 _("Unable to connect to master controller -- Check config\n"));
1406     abort_task = GNUNET_SCHEDULER_add_now (&do_abort, NULL);
1407     return;
1408   }
1409   register_hosts_task = GNUNET_SCHEDULER_add_now (&register_hosts, NULL);
1410   abort_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1411                                              &do_abort, NULL);
1412 }
1413
1414 /**
1415  * Load search strings from given filename. One search string per line.
1416  *
1417  * @param filename filename of the file containing the search strings.
1418  * @param strings set of strings loaded from file. Caller needs to free this
1419  *                if number returned is greater than zero.
1420  * @return number of strings found in the file. GNUNET_SYSERR on error.
1421  */
1422 static int
1423 load_search_strings (const char *filename, char ***strings)
1424 {
1425   char *data;
1426   char *buf;
1427   uint64_t filesize;
1428   unsigned int offset;
1429   int str_cnt;
1430   unsigned int i;
1431
1432   if (NULL == filename)
1433   {
1434     return GNUNET_SYSERR;
1435   }
1436
1437   if (GNUNET_YES != GNUNET_DISK_file_test (filename))
1438   {
1439     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1440                 "Could not find search strings file %s\n", filename);
1441     return GNUNET_SYSERR;
1442   }
1443   if (GNUNET_OK != GNUNET_DISK_file_size (filename, &filesize, GNUNET_YES, GNUNET_YES))
1444     filesize = 0;
1445   if (0 == filesize)
1446   {
1447     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Search strings file %s is empty.\n", filename);
1448     return GNUNET_SYSERR;
1449   }
1450   data = GNUNET_malloc (filesize);
1451   if (filesize != GNUNET_DISK_fn_read (filename, data, filesize))
1452   {
1453     GNUNET_free (data);
1454     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Could not read search strings file %s.\n",
1455          filename);
1456     return GNUNET_SYSERR;
1457   }
1458   buf = data;
1459   offset = 0;
1460   str_cnt = 0;
1461   while (offset < (filesize - 1))
1462   {
1463     offset++;
1464     if (((data[offset] == '\n')) && (buf != &data[offset]))
1465     {
1466       data[offset] = '\0';
1467       str_cnt++;
1468       buf = &data[offset + 1];
1469     }
1470     else if ((data[offset] == '\n') || (data[offset] == '\0'))
1471       buf = &data[offset + 1];
1472   }
1473   *strings = GNUNET_malloc (sizeof (char *) * str_cnt);
1474   offset = 0;
1475   for (i = 0; i < str_cnt; i++)
1476   {
1477     (*strings)[i] = GNUNET_strdup (&data[offset]);
1478     offset += strlen ((*strings)[i]) + 1;
1479   }
1480   free (data);
1481   return str_cnt;
1482 }
1483
1484 /**
1485  * Main function that will be run by the scheduler.
1486  *
1487  * @param cls closure
1488  * @param args remaining command-line arguments
1489  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
1490  * @param config configuration
1491  */
1492 static void
1493 run (void *cls, char *const *args, const char *cfgfile,
1494      const struct GNUNET_CONFIGURATION_Handle *config)
1495 {
1496   unsigned int nhost;
1497
1498   if (NULL == args[0])
1499   {
1500     fprintf (stderr, _("No hosts-file specified on command line. Exiting.\n"));
1501     return;
1502   }
1503   if (NULL == args[1])
1504   {
1505     fprintf (stderr, _("No policy directory specified on command line. Exiting.\n"));
1506     return;
1507   }
1508   num_hosts = GNUNET_TESTBED_hosts_load_from_file (args[0], &hosts);
1509   if (0 == num_hosts)
1510   {
1511     fprintf (stderr, _("No hosts loaded. Need at least one host\n"));
1512     return;
1513   }
1514   for (nhost = 0; nhost < num_hosts; nhost++)
1515   {
1516     if (GNUNET_YES != GNUNET_TESTBED_is_host_habitable (hosts[nhost]))
1517     {
1518       fprintf (stderr, _("Host %s cannot start testbed\n"),
1519                          GNUNET_TESTBED_host_get_hostname (hosts[nhost]));
1520       break;
1521     }
1522   }
1523   if (num_hosts != nhost)
1524   {
1525     fprintf (stderr, _("Exiting\n"));
1526     GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1527     return;
1528   }
1529   if (NULL == config)
1530   {
1531     fprintf (stderr, _("No configuration file given. Exiting\n"));
1532     GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1533     return;
1534   }
1535   if ( (NULL != data_filename) &&
1536        (NULL == (data_file = 
1537                  GNUNET_DISK_file_open (data_filename,
1538                                         GNUNET_DISK_OPEN_READWRITE |
1539                                         GNUNET_DISK_OPEN_TRUNCATE |
1540                                         GNUNET_DISK_OPEN_CREATE,
1541                                         GNUNET_DISK_PERM_USER_READ |
1542                                         GNUNET_DISK_PERM_USER_WRITE))) )
1543     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
1544                               "open",
1545                               data_filename);
1546   if (GNUNET_YES != GNUNET_DISK_directory_test (args[1]))
1547   {
1548     fprintf (stderr, _("Specified policies directory does not exist. Exiting.\n"));
1549     GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1550     return;
1551   }
1552   policy_dir = args[1];
1553   if (GNUNET_YES != GNUNET_DISK_file_test (args[2]))
1554   {
1555     fprintf (stderr, _("No search strings file given. Exiting.\n"));
1556     GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1557     return;
1558   }
1559   num_search_strings = load_search_strings (args[2], &search_strings);
1560   if (0 >= num_search_strings || NULL == search_strings)
1561   {
1562     fprintf (stderr, _("Error loading search strings. Exiting.\n"));
1563     GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1564     return;
1565   }
1566   unsigned int i;
1567   for (i = 0; i < num_search_strings; i++)
1568     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "search string: %s\n", search_strings[i]);
1569   cfg = GNUNET_CONFIGURATION_dup (config);
1570   mc_proc =
1571       GNUNET_TESTBED_controller_start (GNUNET_TESTBED_host_get_hostname
1572                                        (hosts[0]),
1573                                        hosts[0],
1574                                        cfg,
1575                                        status_cb,
1576                                        NULL);
1577   abort_task =
1578       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
1579                                     (GNUNET_TIME_UNIT_SECONDS, 5), &do_abort,
1580                                     NULL);
1581 }
1582
1583
1584 /**
1585  * Main function.
1586  *
1587  * @param argc argument count
1588  * @param argv argument values
1589  * @return 0 on success
1590  */
1591 int
1592 main (int argc, char *const *argv)
1593 {
1594   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
1595     {'d', "details", "FILENAME",
1596      gettext_noop ("name of the file for writing statistics"),
1597      1, &GNUNET_GETOPT_set_string, &data_filename},
1598     { 'n', "linking-factor", "FACTOR",
1599       gettext_noop ("create FACTOR times number of peers random links"),
1600       GNUNET_YES, &GNUNET_GETOPT_set_uint, &linking_factor },
1601     { 'e', "num-errors", "COUNT",
1602       gettext_noop ("tolerate COUNT number of continious timeout failures"),
1603       GNUNET_YES, &GNUNET_GETOPT_set_uint, &num_cont_fails },
1604     { 't', "matching-timeout", "TIMEOUT",
1605       gettext_noop ("wait TIMEOUT seconds before considering a string match as failed"),
1606       GNUNET_YES, &GNUNET_GETOPT_set_relative_time, &search_timeout },
1607     { 's', "search-delay", "DELAY",
1608       gettext_noop ("wait DELAY minutes before starting string search"),
1609       GNUNET_YES, &GNUNET_GETOPT_set_relative_time, &search_delay },
1610     GNUNET_GETOPT_OPTION_END
1611   };
1612   int ret;
1613
1614   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
1615     return 2;
1616
1617   result = GNUNET_SYSERR;
1618   ret =
1619       GNUNET_PROGRAM_run (argc, argv, "gnunet-regex-profiler [OPTIONS] hosts-file policy-dir search-strings-file",
1620                           _("Profiler for regex/mesh"),
1621                           options, &run, NULL);
1622   if (GNUNET_OK != ret)
1623     return ret;
1624   if (GNUNET_OK != result)
1625     return 1;
1626   return 0;
1627 }