- Added a new regex to test_mesh_regex
[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 #include <string.h>
29
30 #include "platform.h"
31 #include "gnunet_applications.h"
32 #include "gnunet_util_lib.h"
33 #include "gnunet_mesh_service.h"
34 #include "gnunet_stream_lib.h"
35 #include "gnunet_testbed_service.h"
36
37 /**
38  * DLL of operations
39  */
40 struct DLLOperation
41 {
42   /**
43    * The testbed operation handle
44    */
45   struct GNUNET_TESTBED_Operation *op;
46
47   /**
48    * Closure
49    */
50   void *cls;
51
52   /**
53    * The next pointer for DLL
54    */
55   struct DLLOperation *next;
56
57   /**
58    * The prev pointer for DLL
59    */
60   struct DLLOperation *prev;
61 };
62
63
64 /**
65  * Available states during profiling
66  */
67 enum State
68 {
69   /**
70    * Initial state
71    */
72   STATE_INIT = 0,
73
74   /**
75    * Starting slaves
76    */
77   STATE_SLAVES_STARTING,
78
79   /**
80    * Creating peers
81    */
82   STATE_PEERS_CREATING,
83
84   /**
85    * Starting peers
86    */
87   STATE_PEERS_STARTING,
88
89   /**
90    * Linking peers
91    */
92   STATE_PEERS_LINKING,
93
94   /**
95    * Destroying peers; we can do this as the controller takes care of stopping a
96    * peer if it is running
97    */
98   STATE_PEERS_DESTROYING
99 };
100
101
102 /**
103  * An array of hosts loaded from the hostkeys file
104  */
105 static struct GNUNET_TESTBED_Host **hosts;
106
107 /**
108  * Peer handles.
109  */
110 struct Peer
111 {
112   /**
113    * The actual testbed peer handle.
114    */
115   struct GNUNET_TESTBED_Peer *peer_handle;
116
117   /**
118    * Peer's mesh handle.
119    */
120   struct GNUNET_MESH_Handle *mesh_handle;
121
122   /**
123    * Peer's mesh tunnel handle.
124    */
125   struct GNUNET_MESH_Tunnel *mesh_tunnel_handle;
126
127   /**
128    * Host on which the peer is running.
129    */
130   struct GNUNET_TESTBED_Host *host_handle;
131
132   /**
133    * Testbed operation handle.
134    */
135   struct GNUNET_TESTBED_Operation *op_handle;
136
137   /**
138    * Filename of the peer's policy file.
139    */
140   char *policy_file;
141 };
142
143 /**
144  * Array of peer handles used to pass to
145  * GNUNET_TESTBED_overlay_configure_topology
146  */
147 struct GNUNET_TESTBED_Peer **peer_handles;
148
149 /**
150  * The array of peers; we fill this as the peers are given to us by the testbed
151  */
152 static struct Peer *peers;
153
154 /**
155  * Host registration handle
156  */
157 static struct GNUNET_TESTBED_HostRegistrationHandle *reg_handle;
158
159 /**
160  * Handle to the master controller process
161  */
162 struct GNUNET_TESTBED_ControllerProc *mc_proc;
163
164 /**
165  * Handle to the master controller
166  */
167 struct GNUNET_TESTBED_Controller *mc;
168
169 /**
170  * Handle to global configuration
171  */
172 struct GNUNET_CONFIGURATION_Handle *cfg;
173
174 /**
175  * Head of the operations list
176  */
177 struct DLLOperation *dll_op_head;
178
179 /**
180  * Tail of the operations list
181  */
182 struct DLLOperation *dll_op_tail;
183
184 /**
185  * Peer linking - topology operation
186  */
187 struct GNUNET_TESTBED_Operation *topology_op;
188
189 /**
190  * Abort task identifier
191  */
192 static GNUNET_SCHEDULER_TaskIdentifier abort_task;
193
194 /**
195  * Host registration task identifier
196  */
197 static GNUNET_SCHEDULER_TaskIdentifier register_hosts_task;
198
199 /**
200  * Global event mask for all testbed events
201  */
202 uint64_t event_mask;
203
204 /**
205  * The starting time of a profiling step
206  */
207 struct GNUNET_TIME_Absolute prof_start_time;
208
209 /**
210  * Duration profiling step has taken
211  */
212 struct GNUNET_TIME_Relative prof_time;
213
214 /**
215  * Current peer id
216  */
217 unsigned int peer_id;
218
219 /**
220  * Number of peers to be started by the profiler
221  */
222 static unsigned int num_peers;
223
224 /**
225  * Number of hosts in the hosts array
226  */
227 static unsigned int num_hosts;
228
229 /**
230  * Number of random links to be established between peers
231  */
232 static unsigned int num_links;
233
234 /**
235  * Global testing status
236  */
237 static int result;
238
239 /**
240  * current state of profiling
241  */
242 enum State state;
243
244
245 /**
246  * Folder where policy files are stored.
247  */
248 static char * policy_dir;
249
250 /**
251  * Search string.
252  */
253 static char *search_string = "GNUNETVPN0001000IPEX401110011101100100000111";
254
255 /**
256  * Search task identifier
257  */
258 static GNUNET_SCHEDULER_TaskIdentifier search_task;
259
260
261 /**
262  * Shutdown nicely
263  *
264  * @param cls NULL
265  * @param tc the task context
266  */
267 static void
268 do_shutdown (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
269 {
270   struct DLLOperation *dll_op;
271   unsigned int nhost;
272   int peer_cnt;
273
274   if (GNUNET_SCHEDULER_NO_TASK != abort_task)
275     GNUNET_SCHEDULER_cancel (abort_task);
276   if (GNUNET_SCHEDULER_NO_TASK != register_hosts_task)
277     GNUNET_SCHEDULER_cancel (register_hosts_task);
278   if (NULL != reg_handle)
279     GNUNET_TESTBED_cancel_registration (reg_handle);
280   if (NULL != topology_op)
281     GNUNET_TESTBED_operation_cancel (topology_op);
282   for (nhost = 0; nhost < num_hosts; nhost++)
283     if (NULL != hosts[nhost])
284       GNUNET_TESTBED_host_destroy (hosts[nhost]);
285   GNUNET_free_non_null (hosts);
286   while (NULL != (dll_op = dll_op_head))
287   {
288     GNUNET_TESTBED_operation_cancel (dll_op->op);
289     GNUNET_CONTAINER_DLL_remove (dll_op_head, dll_op_tail, dll_op);
290     GNUNET_free (dll_op);
291   }
292   for (peer_cnt = 0; peer_cnt < num_peers; peer_cnt++)
293   {
294     if (NULL != peers[peer_cnt].op_handle)
295       GNUNET_TESTBED_operation_cancel (peers[peer_cnt].op_handle);
296   }
297   if (NULL != mc)
298     GNUNET_TESTBED_controller_disconnect (mc);
299   if (NULL != mc_proc)
300     GNUNET_TESTBED_controller_stop (mc_proc);
301   if (NULL != cfg)
302     GNUNET_CONFIGURATION_destroy (cfg);
303
304   GNUNET_SCHEDULER_shutdown (); /* Stop scheduler to shutdown testbed run */
305 }
306
307
308 /**
309  * abort task to run on test timed out
310  *
311  * @param cls NULL
312  * @param tc the task context
313  */
314 static void
315 do_abort (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
316 {
317   GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Aborting\n");
318   abort_task = GNUNET_SCHEDULER_NO_TASK;
319   result = GNUNET_SYSERR;
320   GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
321 }
322
323
324 /**
325  * Method called whenever another peer has added us to a tunnel
326  * the other peer initiated.
327  * Only called (once) upon reception of data with a message type which was
328  * subscribed to in GNUNET_MESH_connect. A call to GNUNET_MESH_tunnel_destroy
329  * causes te tunnel to be ignored and no further notifications are sent about
330  * the same tunnel.
331  *
332  * @param cls closure
333  * @param tunnel new handle to the tunnel
334  * @param initiator peer that started the tunnel
335  * @param atsi performance information for the tunnel
336  * @return initial tunnel context for the tunnel
337  *         (can be NULL -- that's not an error)
338  */
339 void *
340 mesh_inbound_tunnel_handler (void *cls, struct GNUNET_MESH_Tunnel *tunnel,
341                              const struct GNUNET_PeerIdentity *initiator,
342                              const struct GNUNET_ATS_Information *atsi)
343 {
344   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh inbound tunnel handler.\n");
345
346   return NULL;
347 }
348
349
350 /**
351  * Function called whenever an inbound tunnel is destroyed.  Should clean up
352  * any associated state.  This function is NOT called if the client has
353  * explicitly asked for the tunnel to be destroyed using
354  * GNUNET_MESH_tunnel_destroy. It must NOT call GNUNET_MESH_tunnel_destroy on
355  * the tunnel.
356  *
357  * @param cls closure (set from GNUNET_MESH_connect)
358  * @param tunnel connection to the other end (henceforth invalid)
359  * @param tunnel_ctx place where local state associated
360  *                   with the tunnel is stored
361  */
362 void
363 mesh_tunnel_end_handler (void *cls, const struct GNUNET_MESH_Tunnel *tunnel,
364                          void *tunnel_ctx)
365 {
366   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh tunnel end handler.\n");
367 }
368
369
370 /**
371  * Method called whenever a peer has disconnected from the tunnel.
372  * Implementations of this callback must NOT call
373  * GNUNET_MESH_tunnel_destroy immediately, but instead schedule those
374  * to run in some other task later.  However, calling
375  * "GNUNET_MESH_notify_transmit_ready_cancel" is allowed.
376  *
377  * @param cls closure
378  * @param peer_id peer identity the tunnel stopped working with
379  */
380 void
381 mesh_peer_disconnect_handler (void *cls,
382                               const struct GNUNET_PeerIdentity * peer_id)
383 {
384   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh peer disconnect handler.\n");
385 }
386
387
388 /**
389  * Method called whenever a peer has connected to the tunnel.
390  *
391  * @param cls closure
392  * @param peer_id peer identity the tunnel was created to, NULL on timeout
393  * @param atsi performance data for the connection
394  *
395  */
396 void
397 mesh_peer_connect_handler (void *cls,
398                            const struct GNUNET_PeerIdentity* peer_id,
399                            const struct GNUNET_ATS_Information * atsi)
400 {
401   //  struct Peer *peer = (struct Peer *)cls;
402   unsigned int peer_cnt;
403
404   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Mesh peer connect handler.\n");
405
406   for (peer_cnt = 0; peer_cnt < num_peers; peer_cnt++)
407   {
408     GNUNET_TESTBED_operation_done (peers[peer_cnt].op_handle);
409   }
410 }
411
412
413 /**
414  * Connect by string task that is run to search for a string in the NFA
415  *
416  * @param cls NULL
417  * @param tc the task context
418  */
419 static void
420 do_connect_by_string (void *cls,
421                       const struct GNUNET_SCHEDULER_TaskContext * tc)
422 {
423   printf ("Searching for string \"%s\"\n", search_string);
424
425   peers[0].mesh_tunnel_handle = GNUNET_MESH_tunnel_create (peers[0].mesh_handle,
426                                                            NULL,
427                                                            &mesh_peer_connect_handler,
428                                                            &mesh_peer_disconnect_handler,
429                                                            &peers[0]);
430
431
432   GNUNET_MESH_peer_request_connect_by_string (peers[0].mesh_tunnel_handle,
433                                               search_string);
434 }
435
436
437 /**
438  * Mesh connect callback.
439  *
440  * @param cls internal peer id.
441  * @param op operation handle.
442  * @param ca_result connect adapter result.
443  * @param emsg error message.
444  */
445 void
446 mesh_connect_cb (void *cls, struct GNUNET_TESTBED_Operation *op,
447                  void *ca_result, const char *emsg)
448 {
449   static unsigned int connected_mesh_handles;
450   struct Peer *peer = (struct Peer *) cls;
451   char *regex;
452   char *data;
453   char *buf;
454   uint64_t filesize;
455   unsigned int offset;
456
457   if (NULL != emsg)
458   {
459     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Mesh connect failed: %s\n", emsg);
460     GNUNET_assert (0);
461   }
462
463   GNUNET_assert (peer->op_handle == op);
464   GNUNET_assert (peer->mesh_handle == ca_result);
465   GNUNET_assert (NULL != peer->policy_file);
466
467   printf ("Announcing regexes for peer with file %s\n", peer->policy_file);
468   fflush (stdout);
469
470   if (GNUNET_YES != GNUNET_DISK_file_test (peer->policy_file))
471   {
472     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
473                 "Could not find policy file %s\n", peer->policy_file);
474     GNUNET_TESTBED_operation_done (peer->op_handle);
475     return;
476   }
477   if (GNUNET_OK != GNUNET_DISK_file_size (peer->policy_file, &filesize, GNUNET_YES, GNUNET_YES))
478     filesize = 0;
479   if (0 == filesize)
480   {
481     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Policy file %s is empty.\n", peer->policy_file);
482     GNUNET_TESTBED_operation_done (peer->op_handle);
483     return;
484   }
485   data = GNUNET_malloc (filesize);
486   if (filesize != GNUNET_DISK_fn_read (peer->policy_file, data, filesize))
487   {
488     GNUNET_free (data);
489     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Could not read policy file %s.\n",
490          peer->policy_file);
491     GNUNET_TESTBED_operation_done (peer->op_handle);
492     return;
493   }
494   buf = data;
495   offset = 0;
496   regex = NULL;
497   while (offset < (filesize - 1))
498   {
499     offset++;
500     if (((data[offset] == '\n')) && (buf != &data[offset]))
501     {
502       data[offset] = '\0';
503       regex = buf;
504       GNUNET_assert (NULL != regex);
505       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Announcing regex: %s\n", regex);
506       GNUNET_MESH_announce_regex (peer->mesh_handle, regex);
507       buf = &data[offset + 1];
508     }
509     else if ((data[offset] == '\n') || (data[offset] == '\0'))
510       buf = &data[offset + 1];
511   }
512   GNUNET_free (data);
513
514   if (++connected_mesh_handles == num_peers)
515   {
516     printf ("\nAll mesh handles connected.\n");
517
518     search_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
519                                                 (GNUNET_TIME_UNIT_SECONDS, 5),
520                                                 &do_connect_by_string, NULL);
521   }
522
523 }
524
525
526 /**
527  * Mesh connect adapter.
528  *
529  * @param cls not used.
530  * @param cfg configuration handle.
531  *
532  * @return
533  */
534 void *
535 mesh_ca (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg)
536 {
537   struct Peer *peer = (struct Peer *) cls;
538
539   static struct GNUNET_MESH_MessageHandler handlers[] = {
540     {NULL, 0, 0}
541   };
542
543   static GNUNET_MESH_ApplicationType apptypes[] = {
544     GNUNET_APPLICATION_TYPE_END
545   };
546
547   peer->mesh_handle =
548       GNUNET_MESH_connect (cfg, cls, &mesh_inbound_tunnel_handler,
549                            &mesh_tunnel_end_handler, handlers, apptypes);
550
551   return peer->mesh_handle;
552 }
553
554
555 /**
556  * Adapter function called to destroy a connection to
557  * the mesh service
558  *
559  * @param cls closure
560  * @param op_result service handle returned from the connect adapter
561  */
562 void
563 mesh_da (void *cls, void *op_result)
564 {
565   static unsigned int disconnected_mesh_handles;
566   struct Peer *peer = (struct Peer *) cls;
567
568   GNUNET_assert (peer->mesh_handle == op_result);
569
570   if (NULL != peer->mesh_tunnel_handle)
571     GNUNET_MESH_tunnel_destroy (peer->mesh_tunnel_handle);
572   GNUNET_MESH_disconnect (peer->mesh_handle);
573   peer->mesh_handle = NULL;
574
575   if (++disconnected_mesh_handles == num_peers)
576   {
577     printf ("All mesh handles disconnected.\n");
578     GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
579   }
580
581   GNUNET_MESH_disconnect (peer->mesh_handle);
582   peer->mesh_handle = NULL;
583
584   if (++disconnected_mesh_handles == num_peers)
585   {
586     GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
587   }
588 }
589
590
591 /**
592  * Functions of this signature are called when a peer has been successfully
593  * started or stopped.
594  *
595  * @param cls the closure from GNUNET_TESTBED_peer_start/stop()
596  * @param emsg NULL on success; otherwise an error description
597  */
598 static void
599 peer_churn_cb (void *cls, const char *emsg)
600 {
601   struct DLLOperation *dll_op = cls;
602   struct GNUNET_TESTBED_Operation *op;
603   static unsigned int started_peers;
604   unsigned int peer_cnt;
605
606   op = dll_op->op;
607   GNUNET_CONTAINER_DLL_remove (dll_op_head, dll_op_tail, dll_op);
608   GNUNET_free (dll_op);
609   if (NULL != emsg)
610   {
611     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
612          _("An operation has failed while starting peers\n"));
613     GNUNET_TESTBED_operation_done (op);
614     GNUNET_SCHEDULER_cancel (abort_task);
615     abort_task = GNUNET_SCHEDULER_add_now (&do_abort, NULL);
616     return;
617   }
618   GNUNET_TESTBED_operation_done (op);
619   if (++started_peers == num_peers)
620   {
621     prof_time = GNUNET_TIME_absolute_get_duration (prof_start_time);
622     printf ("All peers started successfully in %.2f seconds\n",
623             ((double) prof_time.rel_value) / 1000.00);
624     result = GNUNET_OK;
625     if (0 == num_links)
626     {
627       GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
628       return;
629     }
630
631     peer_handles = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_Peer *) * num_peers);
632     for (peer_cnt = 0; peer_cnt < num_peers; peer_cnt++)
633       peer_handles[peer_cnt] = peers[peer_cnt].peer_handle;
634
635     state = STATE_PEERS_LINKING;
636     /* Do overlay connect */
637     prof_start_time = GNUNET_TIME_absolute_get ();
638     topology_op =
639         GNUNET_TESTBED_overlay_configure_topology (NULL, num_peers, peer_handles,
640                                                    GNUNET_TESTBED_TOPOLOGY_ERDOS_RENYI,
641                                                    num_links);
642     if (NULL == topology_op)
643     {
644       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
645                   "Cannot create topology, op handle was NULL\n");
646       GNUNET_assert (0);
647     }
648   }
649 }
650
651
652 /**
653  * Functions of this signature are called when a peer has been successfully
654  * created
655  *
656  * @param cls the closure from GNUNET_TESTBED_peer_create()
657  * @param peer the handle for the created peer; NULL on any error during
658  *          creation
659  * @param emsg NULL if peer is not NULL; else MAY contain the error description
660  */
661 static void
662 peer_create_cb (void *cls, struct GNUNET_TESTBED_Peer *peer, const char *emsg)
663 {
664   struct DLLOperation *dll_op = cls;
665   struct Peer *peer_ptr;
666   static unsigned int created_peers;
667   unsigned int peer_cnt;
668
669   if (NULL != emsg)
670   {
671     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
672          _("Creating a peer failed. Error: %s\n"), emsg);
673     GNUNET_TESTBED_operation_done (dll_op->op);
674     GNUNET_CONTAINER_DLL_remove (dll_op_head, dll_op_tail, dll_op);
675     GNUNET_free (dll_op);
676     GNUNET_SCHEDULER_cancel (abort_task);
677     abort_task = GNUNET_SCHEDULER_add_now (&do_abort, NULL);
678     return;
679   }
680
681   peer_ptr = dll_op->cls;
682   GNUNET_assert (NULL == peer_ptr->peer_handle);
683   peer_ptr->peer_handle = peer;
684   GNUNET_TESTBED_operation_done (dll_op->op);
685   GNUNET_CONTAINER_DLL_remove (dll_op_head, dll_op_tail, dll_op);
686   GNUNET_free (dll_op);
687
688   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Peer %i created on host %s\n",
689               created_peers,
690               GNUNET_TESTBED_host_get_hostname (peer_ptr->host_handle));
691
692   if (++created_peers == num_peers)
693   {
694     prof_time = GNUNET_TIME_absolute_get_duration (prof_start_time);
695     printf ("All peers created successfully in %.2f seconds\n",
696             ((double) prof_time.rel_value) / 1000.00);
697     /* Now peers are to be started */
698     state = STATE_PEERS_STARTING;
699     prof_start_time = GNUNET_TIME_absolute_get ();
700     for (peer_cnt = 0; peer_cnt < num_peers; peer_cnt++)
701     {
702       dll_op = GNUNET_malloc (sizeof (struct DLLOperation));
703       dll_op->op = GNUNET_TESTBED_peer_start (dll_op, peers[peer_cnt].peer_handle,
704                                               &peer_churn_cb, dll_op);
705       GNUNET_CONTAINER_DLL_insert_tail (dll_op_head, dll_op_tail, dll_op);
706     }
707   }
708 }
709
710 /**
711  * Function called with a filename.
712  *
713  * @param cls closure
714  * @param filename complete filename (absolute path)
715  * @return GNUNET_OK to continue to iterate,
716  *  GNUNET_SYSERR to abort iteration with error!
717  */
718 int
719 policy_filename_cb (void *cls, const char *filename)
720 {
721   static unsigned int peer_cnt;
722   struct DLLOperation *dll_op;
723
724   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Creating peer %i on host %s for policy file %s\n",
725               peer_cnt,
726               GNUNET_TESTBED_host_get_hostname (hosts[peer_cnt % num_hosts]),
727               filename);
728
729   peers[peer_cnt].policy_file = GNUNET_strdup (filename);
730   peers[peer_cnt].host_handle = hosts[peer_cnt % num_hosts];
731
732   dll_op = GNUNET_malloc (sizeof (struct DLLOperation));
733   dll_op->cls = &peers[peer_cnt];
734   dll_op->op = GNUNET_TESTBED_peer_create (mc,
735                                            hosts[peer_cnt % num_hosts],
736                                            cfg,
737                                            &peer_create_cb,
738                                            dll_op);
739   GNUNET_CONTAINER_DLL_insert_tail (dll_op_head, dll_op_tail, dll_op);
740   peer_cnt++;
741
742   return GNUNET_OK;
743 }
744
745
746 /**
747  * Controller event callback
748  *
749  * @param cls NULL
750  * @param event the controller event
751  */
752 static void
753 controller_event_cb (void *cls,
754                      const struct GNUNET_TESTBED_EventInformation *event)
755 {
756   struct DLLOperation *dll_op;
757   struct GNUNET_TESTBED_Operation *op;
758
759   switch (state)
760   {
761   case STATE_SLAVES_STARTING:
762     switch (event->type)
763     {
764     case GNUNET_TESTBED_ET_OPERATION_FINISHED:
765       {
766         static unsigned int slaves_started;
767
768         dll_op = event->details.operation_finished.op_cls;
769         GNUNET_CONTAINER_DLL_remove (dll_op_head, dll_op_tail, dll_op);
770         GNUNET_free (dll_op);
771         op = event->details.operation_finished.operation;
772         if (NULL != event->details.operation_finished.emsg)
773         {
774           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
775                _("An operation has failed while starting slaves\n"));
776           GNUNET_TESTBED_operation_done (op);
777           GNUNET_SCHEDULER_cancel (abort_task);
778           abort_task = GNUNET_SCHEDULER_add_now (&do_abort, NULL);
779           return;
780         }
781         GNUNET_TESTBED_operation_done (op);
782         /* Proceed to start peers */
783         if (++slaves_started == num_hosts - 1)
784         {
785           printf ("All slaves started successfully\n");
786
787           state = STATE_PEERS_CREATING;
788           prof_start_time = GNUNET_TIME_absolute_get ();
789
790           num_peers = GNUNET_DISK_directory_scan (policy_dir,
791                                                   NULL,
792                                                   NULL);
793           peers = GNUNET_malloc (sizeof (struct Peer) * num_peers);
794
795           GNUNET_DISK_directory_scan (policy_dir,
796                                       &policy_filename_cb,
797                                       NULL);
798         }
799       }
800       break;
801     default:
802       GNUNET_assert (0);
803     }
804     break;
805   case STATE_PEERS_STARTING:
806     switch (event->type)
807     {
808     case GNUNET_TESTBED_ET_OPERATION_FINISHED:
809       /* Control reaches here when peer start fails */
810     case GNUNET_TESTBED_ET_PEER_START:
811       /* we handle peer starts in peer_churn_cb */
812       break;
813     default:
814       GNUNET_assert (0);
815     }
816     break;
817   case STATE_PEERS_LINKING:
818    switch (event->type)
819     {
820     case GNUNET_TESTBED_ET_OPERATION_FINISHED:
821       /* Control reaches here when a peer linking operation fails */
822       if (NULL != event->details.operation_finished.emsg)
823       {
824         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
825              _("An operation has failed while linking\n"));
826         GNUNET_SCHEDULER_cancel (abort_task);
827         abort_task = GNUNET_SCHEDULER_add_now (&do_abort, NULL);
828       }
829       break;
830     case GNUNET_TESTBED_ET_CONNECT:
831       {
832         static unsigned int established_links;
833         unsigned int peer_cnt;
834
835         if (0 == established_links)
836           printf ("Establishing links\n .");
837         else
838         {
839           printf (".");
840           fflush (stdout);
841         }
842         if (++established_links == num_links)
843         {
844           prof_time = GNUNET_TIME_absolute_get_duration (prof_start_time);
845           printf ("\n%u links established in %.2f seconds\n",
846                   num_links, ((double) prof_time.rel_value) / 1000.00);
847           result = GNUNET_OK;
848           GNUNET_free (peer_handles);
849           printf ("\nConnecting to mesh service...\n");
850           for (peer_cnt = 0; peer_cnt < num_peers; peer_cnt++)
851           {
852             peers[peer_cnt].op_handle = GNUNET_TESTBED_service_connect (NULL,
853                                                                         peers[peer_cnt].peer_handle,
854                                                                         "mesh",
855                                                                         &mesh_connect_cb,
856                                                                         &peers[peer_cnt],
857                                                                         &mesh_ca,
858                                                                         &mesh_da,
859                                                                         &peers[peer_cnt]);
860           }
861         }
862       }
863       break;
864     default:
865       GNUNET_assert (0);
866     }
867     break;
868   default:
869     GNUNET_assert (0);
870   }
871 }
872
873
874 /**
875  * Task to register all hosts available in the global host list
876  *
877  * @param cls NULL
878  * @param tc the scheduler task context
879  */
880 static void
881 register_hosts (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
882
883
884 /**
885  * Callback which will be called to after a host registration succeeded or failed
886  *
887  * @param cls the closure
888  * @param emsg the error message; NULL if host registration is successful
889  */
890 static void
891 host_registration_completion (void *cls, const char *emsg)
892 {
893   reg_handle = NULL;
894   if (NULL != emsg)
895   {
896     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
897                 _("Host registration failed for a host. Error: %s\n"), emsg);
898     GNUNET_SCHEDULER_cancel (abort_task);
899     abort_task = GNUNET_SCHEDULER_add_now (&do_abort, NULL);
900     return;
901   }
902   register_hosts_task = GNUNET_SCHEDULER_add_now (&register_hosts, NULL);
903 }
904
905
906 /**
907  * Task to register all hosts available in the global host list
908  *
909  * @param cls NULL
910  * @param tc the scheduler task context
911  */
912 static void
913 register_hosts (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
914 {
915   struct DLLOperation *dll_op;
916   static unsigned int reg_host;
917   unsigned int slave;
918
919   register_hosts_task = GNUNET_SCHEDULER_NO_TASK;
920   if (reg_host == num_hosts - 1)
921   {
922     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
923                 "All hosts successfully registered\n");
924     /* Start slaves */
925     state = STATE_SLAVES_STARTING;
926     for (slave = 1; slave < num_hosts; slave++)
927     {
928       dll_op = GNUNET_malloc (sizeof (struct DLLOperation));
929       dll_op->op = GNUNET_TESTBED_controller_link (dll_op,
930                                                    mc,
931                                                    hosts[slave],
932                                                    hosts[0],
933                                                    cfg,
934                                                    GNUNET_YES);
935       GNUNET_CONTAINER_DLL_insert_tail (dll_op_head, dll_op_tail, dll_op);
936     }
937     return;
938   }
939   reg_handle = GNUNET_TESTBED_register_host (mc, hosts[++reg_host],
940                                              host_registration_completion,
941                                              NULL);
942 }
943
944
945 /**
946  * Callback to signal successfull startup of the controller process
947  *
948  * @param cls the closure from GNUNET_TESTBED_controller_start()
949  * @param config the configuration with which the controller has been started;
950  *          NULL if status is not GNUNET_OK
951  * @param status GNUNET_OK if the startup is successfull; GNUNET_SYSERR if not,
952  *          GNUNET_TESTBED_controller_stop() shouldn't be called in this case
953  */
954 static void
955 status_cb (void *cls, const struct GNUNET_CONFIGURATION_Handle *config, int status)
956 {
957   GNUNET_SCHEDULER_cancel (abort_task);
958   if (GNUNET_OK != status)
959   {
960     mc_proc = NULL;
961     abort_task = GNUNET_SCHEDULER_add_now (&do_abort, NULL);
962     return;
963   }
964   event_mask = 0;
965   event_mask |= (1LL << GNUNET_TESTBED_ET_PEER_START);
966   event_mask |= (1LL << GNUNET_TESTBED_ET_PEER_STOP);
967   event_mask |= (1LL << GNUNET_TESTBED_ET_CONNECT);
968   event_mask |= (1LL << GNUNET_TESTBED_ET_DISCONNECT);
969   event_mask |= (1LL << GNUNET_TESTBED_ET_OPERATION_FINISHED);
970   mc = GNUNET_TESTBED_controller_connect (config, hosts[0], event_mask,
971                                           &controller_event_cb, NULL);
972   if (NULL == mc)
973   {
974     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
975                 _("Unable to connect to master controller -- Check config\n"));
976     abort_task = GNUNET_SCHEDULER_add_now (&do_abort, NULL);
977     return;
978   }
979   register_hosts_task = GNUNET_SCHEDULER_add_now (&register_hosts, NULL);
980   abort_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
981                                              &do_abort, NULL);
982 }
983
984
985 /**
986  * Main function that will be run by the scheduler.
987  *
988  * @param cls closure
989  * @param args remaining command-line arguments
990  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
991  * @param config configuration
992  */
993 static void
994 run (void *cls, char *const *args, const char *cfgfile,
995      const struct GNUNET_CONFIGURATION_Handle *config)
996 {
997   unsigned int nhost;
998
999   if (NULL == args[0])
1000   {
1001     fprintf (stderr, _("No hosts-file specified on command line. Exiting.\n"));
1002     return;
1003   }
1004   if (NULL == args[1])
1005   {
1006     fprintf (stderr, _("No policy directory specified on command line. Exiting.\n"));
1007     return;
1008   }
1009   num_hosts = GNUNET_TESTBED_hosts_load_from_file (args[0], &hosts);
1010   if (0 == num_hosts)
1011   {
1012     fprintf (stderr, _("No hosts loaded. Need at least one host\n"));
1013     return;
1014   }
1015   for (nhost = 0; nhost < num_hosts; nhost++)
1016   {
1017     if (GNUNET_YES != GNUNET_TESTBED_is_host_habitable (hosts[nhost]))
1018     {
1019       fprintf (stderr, _("Host %s cannot start testbed\n"),
1020                          GNUNET_TESTBED_host_get_hostname (hosts[nhost]));
1021       break;
1022     }
1023   }
1024   if (num_hosts != nhost)
1025   {
1026     fprintf (stderr, _("Exiting\n"));
1027     GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1028     return;
1029   }
1030   if (NULL == config)
1031   {
1032     fprintf (stderr, _("No configuration file given. Exiting\n"));
1033     GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1034     return;
1035   }
1036   if (GNUNET_YES != GNUNET_DISK_directory_test (args[1]))
1037   {
1038     fprintf (stderr, _("Specified policies directory does not exist. Exiting.\n"));
1039     GNUNET_SCHEDULER_add_now (&do_shutdown, NULL);
1040     return;
1041   }
1042   policy_dir = args[1];
1043
1044   cfg = GNUNET_CONFIGURATION_dup (config);
1045   mc_proc =
1046       GNUNET_TESTBED_controller_start (GNUNET_TESTBED_host_get_hostname
1047                                        (hosts[0]),
1048                                        hosts[0],
1049                                        cfg,
1050                                        status_cb,
1051                                        NULL);
1052   abort_task =
1053       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
1054                                     (GNUNET_TIME_UNIT_SECONDS, 5), &do_abort,
1055                                     NULL);
1056 }
1057
1058
1059 /**
1060  * Main function.
1061  *
1062  * @param argc argument count
1063  * @param argv argument values
1064  * @return 0 on success
1065  */
1066 int
1067 main (int argc, char *const *argv)
1068 {
1069   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
1070     { 'n', "num-links", "COUNT",
1071       gettext_noop ("create COUNT number of random links"),
1072       GNUNET_YES, &GNUNET_GETOPT_set_uint, &num_links },
1073     GNUNET_GETOPT_OPTION_END
1074   };
1075   int ret;
1076
1077   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
1078     return 2;
1079
1080   result = GNUNET_SYSERR;
1081   ret =
1082       GNUNET_PROGRAM_run (argc, argv, "gnunet-regex-profiler [OPTIONS] hosts-file policy-dir",
1083                           _("Profiler for regex/mesh"),
1084                           options, &run, NULL);
1085   if (GNUNET_OK != ret)
1086     return ret;
1087   if (GNUNET_OK != result)
1088     return 1;
1089   return 0;
1090 }