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