sensor: profiler prompts for peer reconnection
[oweals/gnunet.git] / src / sensor / gnunet-sensor-profiler.c
1 /*
2      This file is part of GNUnet.
3      (C)
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 sensor/gnunet-sensor-profiler.c
23  * @brief Profiler for the sensor service
24  * @author Omar Tarabai
25  */
26 #include "platform.h"
27 #include "gnunet_util_lib.h"
28 #include "gnunet_testbed_service.h"
29 #include "gnunet_peerstore_service.h"
30 #include "gnunet_sensor_service.h"
31 #include "gnunet_sensor_util_lib.h"
32 #include "gnunet_transport_service.h"
33
34 /**
35  * Time to wait for the peer to startup completely
36  */
37 #define PEER_STARTUP_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
38
39 /**
40  * Information about a single peer
41  */
42 struct PeerInfo
43 {
44
45   /**
46    * Peer Identity
47    */
48   struct GNUNET_PeerIdentity peer_id;
49
50   /**
51    * Testbed peer handle
52    */
53   struct GNUNET_TESTBED_Peer *testbed_peer;
54
55   /**
56    * Index of this peer within our list
57    */
58   int index;
59
60 };
61
62 struct DisconnectionContext
63 {
64
65   struct DisconnectionContext *prev;
66
67   struct DisconnectionContext *next;
68
69   struct PeerInfo *p1;
70
71   struct PeerInfo *p2;
72
73   struct GNUNET_TESTBED_Operation *p1_transport_op;
74
75   struct GNUNET_TRANSPORT_Blacklist *blacklist;
76
77 };
78
79 struct ConnectionContext
80 {
81
82   struct PeerInfo *p1;
83
84   struct PeerInfo *p2;
85
86 };
87
88
89 /**
90  * Name of the configuration file used
91  */
92 static const char *cfg_filename = "gnunet-sensor-profiler.conf";
93
94 /**
95  * Directory to read sensor definitions from
96  */
97 static const char *sensor_src_dir = "sensors";
98
99 /**
100  * Directory to write new sensor definitions to
101  */
102 static const char *sensor_dst_dir = "/tmp/gnunet-sensor-profiler";
103
104 /**
105  * Scheduled task to shutdown
106  */
107 static GNUNET_SCHEDULER_TaskIdentifier shutdown_task = GNUNET_SCHEDULER_NO_TASK;
108
109 /**
110  * GNUnet configuration
111  */
112 static struct GNUNET_CONFIGURATION_Handle *cfg;
113
114 /**
115  * Number of peers to run (Option -p)
116  */
117 static unsigned int num_peers = 0;
118
119 /**
120  * Set sensors running interval to this value (Option -i)
121  */
122 static unsigned int sensors_interval = 0;
123
124 /**
125  * Path to topology file (Option -t)
126  */
127 static char *topology_file;
128
129 /**
130  * Array of peer info for all peers
131  */
132 static struct PeerInfo *all_peers_info;
133
134 /**
135  * Number of peers that we already collected and start their info
136  */
137 static int peers_known = 0;
138
139 /**
140  * TESTBED operation connecting us to peerstore service on collection point
141  */
142 static struct GNUNET_TESTBED_Operation *peerstore_op;
143
144 /**
145  * Handle to peerstore service on collection point
146  */
147 static struct GNUNET_PEERSTORE_Handle *peerstore;
148
149 /**
150  * Dashboard service on collection point started?
151  */
152 static int dashboard_service_started = GNUNET_NO;
153
154 /**
155  * Number of peers started the sensor service successfully
156  */
157 static int sensor_services_started = 0;
158
159 /**
160  * Array of sensor names to be used for watching peerstore records
161  */
162 static char **sensor_names;
163
164 /**
165  * Size of 'sensor_names' array
166  */
167 static unsigned int sensor_names_size = 0;
168
169 /**
170  * Task run after any waiting period
171  */
172 static GNUNET_SCHEDULER_TaskIdentifier delayed_task = GNUNET_SCHEDULER_NO_TASK;
173
174 /**
175  * Head of list of disconnection contexts
176  */
177 static struct DisconnectionContext *dc_head;
178
179 /*
180  * Tail of list of disconnection contexts
181  */
182 static struct DisconnectionContext *dc_tail;
183
184
185 /**
186  * Copy directory recursively
187  *
188  * @param src Path to source directory
189  * @param dst Destination directory, will be created if it does not exist
190  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
191  */
192 static int
193 copy_dir (const char *src, const char *dst);
194
195
196 /**
197  * Prompt the user to disconnect two peers
198  */
199 static void
200 prompt_peer_disconnection ();
201
202
203 /**
204  * Destroy a DisconnectionContext struct
205  */
206 static void
207 destroy_dc (struct DisconnectionContext *dc)
208 {
209   if (NULL != dc->blacklist)
210   {
211     GNUNET_TRANSPORT_blacklist_cancel (dc->blacklist);
212     dc->blacklist = NULL;
213   }
214   if (NULL != dc->p1_transport_op)
215   {
216     GNUNET_TESTBED_operation_done (dc->p1_transport_op);
217     dc->p1_transport_op = NULL;
218   }
219   GNUNET_free (dc);
220 }
221
222
223 /**
224  * Do clean up and shutdown scheduler
225  */
226 static void
227 do_shutdown (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
228 {
229   int i;
230   struct DisconnectionContext *dc;
231
232   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Shutting down.\n");
233   if (GNUNET_SCHEDULER_NO_TASK != delayed_task)
234   {
235     GNUNET_SCHEDULER_cancel (delayed_task);
236     delayed_task = GNUNET_SCHEDULER_NO_TASK;
237   }
238   dc = dc_head;
239   while (NULL != dc)
240   {
241     GNUNET_CONTAINER_DLL_remove (dc_head, dc_tail, dc);
242     destroy_dc (dc);
243     dc = dc_head;
244   }
245   if (NULL != peerstore_op)
246   {
247     GNUNET_TESTBED_operation_done (peerstore_op);
248     peerstore_op = NULL;
249   }
250   if (NULL != all_peers_info)
251   {
252     GNUNET_free (all_peers_info);
253     all_peers_info = NULL;
254   }
255   if (NULL != cfg)
256   {
257     GNUNET_CONFIGURATION_destroy (cfg);
258     cfg = NULL;
259   }
260   if (NULL != sensor_names)
261   {
262     for (i = 0; i < sensor_names_size; i++)
263       GNUNET_free (sensor_names[i]);
264     GNUNET_array_grow (sensor_names, sensor_names_size, 0);
265   }
266   GNUNET_SCHEDULER_shutdown ();
267 }
268
269
270 /*****************************************************************************/
271 /****************************** DISCONNECT PEERS *****************************/
272 /*****************************************************************************/
273
274
275 /**
276  * Function to call with result of the TRANSPORT try disconnect request.
277  *
278  * @param cls closure
279  * @param result #GNUNET_OK if message was transmitted to transport service
280  *               #GNUNET_SYSERR if message was not transmitted to transport service
281  */
282 static void
283 transport_disconnect_cb (void *cls, const int result)
284 {
285   struct DisconnectionContext *dc = cls;
286
287   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
288               "Peer disconnection request sent: %d,%d\n", dc->p1->index,
289               dc->p2->index);
290 }
291
292
293 /**
294  * Callback to be called when transport service connect operation is completed
295  *
296  * @param cls the callback closure from functions generating an operation
297  * @param op the operation that has been finished
298  * @param ca_result the service handle returned from GNUNET_TESTBED_ConnectAdapter()
299  * @param emsg error message in case the operation has failed; will be NULL if
300  *          operation has executed successfully.
301  */
302 static void
303 transport_connect_cb (void *cls, struct GNUNET_TESTBED_Operation *op,
304                       void *ca_result, const char *emsg)
305 {
306   struct DisconnectionContext *dc = cls;
307   struct GNUNET_TRANSPORT_Handle *transport = ca_result;
308
309   if (NULL != emsg)
310   {
311     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ERROR: %s.\n", emsg);
312     GNUNET_assert (0);
313   }
314   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "transport_connect_cb().\n");
315   GNUNET_TRANSPORT_try_disconnect (transport, &dc->p2->peer_id,
316                                    &transport_disconnect_cb, dc);
317 }
318
319
320 /**
321  * Callback from TRANSPORT service to ask if the given peer ID is blacklisted.
322  *
323  * @param cls closure, DisconnectionContext
324  * @param pid peer to approve or disapproave
325  * @return #GNUNET_OK if the connection is allowed, #GNUNET_SYSERR if not
326  */
327 static int
328 blacklist_cb (void *cls, const struct GNUNET_PeerIdentity *pid)
329 {
330   struct DisconnectionContext *dc = cls;
331
332   if (0 == GNUNET_CRYPTO_cmp_peer_identity (&dc->p2->peer_id, pid))
333     return GNUNET_SYSERR;
334   return GNUNET_OK;
335 }
336
337
338 /**
339  * Adapter function called to establish a connection to transport service.
340  *
341  * @param cls closure
342  * @param cfg configuration of the peer to connect to; will be available until
343  *          GNUNET_TESTBED_operation_done() is called on the operation returned
344  *          from GNUNET_TESTBED_service_connect()
345  * @return service handle to return in 'op_result', NULL on error
346  */
347 static void *
348 transport_connect_adapter (void *cls,
349                            const struct GNUNET_CONFIGURATION_Handle *cfg)
350 {
351   struct DisconnectionContext *dc = cls;
352   struct GNUNET_TRANSPORT_Handle *transport;
353
354   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "transport_connect_adapter().\n");
355   dc->blacklist = GNUNET_TRANSPORT_blacklist (cfg, &blacklist_cb, dc);
356   GNUNET_assert (NULL != dc->blacklist);
357   transport = GNUNET_TRANSPORT_connect (cfg, NULL, NULL, NULL, NULL, NULL);
358   GNUNET_assert (NULL != transport);
359   return transport;
360 }
361
362
363 /**
364  * Adapter function called to destroy a connection to transport service.
365  *
366  * @param cls closure
367  * @param op_result service handle returned from the connect adapter
368  */
369 static void
370 transport_disconnect_adapter (void *cls, void *op_result)
371 {
372   struct GNUNET_TRANSPORT_Handle *transport = op_result;
373
374   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "transport_disconnect_adapter().\n");
375   GNUNET_TRANSPORT_disconnect (transport);
376 }
377
378
379 /**
380  * Kill any connection between two peers. Has no effect if the peers are not
381  * connected.
382  */
383 static void
384 disconnect_peers (struct PeerInfo *p1, struct PeerInfo *p2)
385 {
386   struct DisconnectionContext *dc;
387
388   GNUNET_assert (p1 != p2);
389   dc = GNUNET_new (struct DisconnectionContext);
390
391   dc->p1 = p1;
392   dc->p2 = p2;
393   GNUNET_CONTAINER_DLL_insert (dc_head, dc_tail, dc);
394   dc->p1_transport_op =
395       GNUNET_TESTBED_service_connect (NULL, p1->testbed_peer, "transport",
396                                       &transport_connect_cb, dc,
397                                       &transport_connect_adapter,
398                                       &transport_disconnect_adapter, dc);
399 }
400
401
402 /*****************************************************************************/
403 /**************************** END DISCONNECT PEERS ***************************/
404 /*****************************************************************************/
405
406 /*****************************************************************************/
407 /******************************* CONNECT PEERS *******************************/
408 /*****************************************************************************/
409
410 /**
411  * Callback to be called when overlay connection operation is completed
412  *
413  * @param cls the callback closure from functions generating an operation
414  * @param op the operation that has been finished
415  * @param emsg error message in case the operation has failed; will be NULL if
416  *          operation has executed successfully.
417  */
418 static void
419 overlay_connect_cb (void *cls, struct GNUNET_TESTBED_Operation *op,
420                       const char *emsg)
421 {
422   struct ConnectionContext *cc = cls;
423
424   if (NULL != emsg)
425   {
426     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ERROR: %s.\n", emsg);
427     GNUNET_assert (0);
428   }
429   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Peer connection request sent: %d,%d\n",
430               cc->p1->index, cc->p2->index);
431   GNUNET_free (cc);
432   GNUNET_TESTBED_operation_done (op);
433 }
434
435
436 /**
437  * Connect two peers together
438  */
439 static void
440 connect_peers (struct PeerInfo *p1, struct PeerInfo *p2)
441 {
442   struct DisconnectionContext *dc;
443   struct ConnectionContext *cc;
444
445   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "connect_peers()\n");
446   /* Check if we have a disconnection request before */
447   dc = dc_head;
448   while (NULL != dc)
449   {
450     if ((dc->p1 == p1 && dc->p2 == p2) || (dc->p1 == p2 && dc->p2 == p1))
451       break;
452     dc = dc_head->next;
453   }
454   if (NULL != dc)
455   {
456     GNUNET_CONTAINER_DLL_remove (dc_head, dc_tail, dc);
457     destroy_dc (dc);
458   }
459   /* Connect peers using testbed */
460   cc = GNUNET_new (struct ConnectionContext);
461   cc->p1 = p1;
462   cc->p2 = p2;
463   GNUNET_TESTBED_overlay_connect (cc, &overlay_connect_cb, cc,
464                                   p1->testbed_peer, p2->testbed_peer);
465 }
466
467 /*****************************************************************************/
468 /****************************** END CONNECT PEERS ****************************/
469 /*****************************************************************************/
470
471 /**
472  * Function called with each file/folder inside a directory that is being copied.
473  *
474  * @param cls closure, destination directory
475  * @param filename complete filename (absolute path)
476  * @return #GNUNET_OK to continue to iterate.
477  *         #GNUNET_SYSERR to abort iteration with error
478  */
479 static int
480 copy_dir_scanner (void *cls, const char *filename)
481 {
482   char *dst_dir = cls;
483   char *dst;
484   int copy_result;
485
486   GNUNET_asprintf (&dst, "%s%s%s", dst_dir, DIR_SEPARATOR_STR,
487                    GNUNET_STRINGS_get_short_name (filename));
488   if (GNUNET_YES == GNUNET_DISK_directory_test (filename, GNUNET_YES))
489     copy_result = copy_dir (filename, dst);
490   else
491   {
492     if (GNUNET_YES == GNUNET_DISK_file_test (dst))
493       GNUNET_DISK_directory_remove (dst);
494     copy_result = GNUNET_DISK_file_copy (filename, dst);
495     if (GNUNET_OK == copy_result)
496       GNUNET_DISK_fix_permissions (dst, GNUNET_NO, GNUNET_NO);
497   }
498   GNUNET_free (dst);
499   return copy_result;
500 }
501
502
503 /**
504  * Copy directory recursively
505  *
506  * @param src Path to source directory
507  * @param dst Destination directory, will be created if it does not exist
508  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
509  */
510 static int
511 copy_dir (const char *src, const char *dst)
512 {
513   if (GNUNET_YES != GNUNET_DISK_directory_test (src, GNUNET_YES))
514     return GNUNET_SYSERR;
515   if (GNUNET_OK != GNUNET_DISK_directory_create (dst))
516     return GNUNET_SYSERR;
517   if (GNUNET_SYSERR ==
518       GNUNET_DISK_directory_scan (src, &copy_dir_scanner, (char *) dst))
519     return GNUNET_SYSERR;
520   return GNUNET_OK;
521 }
522
523
524 /**
525  * Function called with each file/folder inside source sensor directory.
526  *
527  * @param cls closure (unused)
528  * @param filename complete filename (absolute path)
529  * @return #GNUNET_OK to continue to iterate.
530  */
531 static int
532 sensor_dir_scanner (void *cls, const char *filename)
533 {
534   const char *file_basename;
535   char *dst_path;
536   struct GNUNET_CONFIGURATION_Handle *sensor_cfg;
537   char *sensor_name;
538
539   file_basename = GNUNET_STRINGS_get_short_name (filename);
540   GNUNET_asprintf (&dst_path, "%s%s%s", sensor_dst_dir, DIR_SEPARATOR_STR,
541                    file_basename);
542   if (GNUNET_YES == GNUNET_DISK_directory_test (filename, GNUNET_NO))
543   {
544     GNUNET_assert (GNUNET_OK == copy_dir (filename, dst_path));
545   }
546   else
547   {
548     sensor_name = GNUNET_strdup (file_basename);
549     GNUNET_array_append (sensor_names, sensor_names_size, sensor_name);
550     sensor_cfg = GNUNET_CONFIGURATION_create ();
551     GNUNET_assert (GNUNET_OK ==
552                    GNUNET_CONFIGURATION_parse (sensor_cfg, filename));
553     GNUNET_CONFIGURATION_set_value_string (sensor_cfg, file_basename,
554                                            "COLLECTION_POINT",
555                                            GNUNET_i2s_full (&all_peers_info[0].
556                                                             peer_id));
557     if (sensors_interval > 0)
558     {
559       GNUNET_CONFIGURATION_set_value_number (sensor_cfg, file_basename,
560                                              "INTERVAL",
561                                              (unsigned long long int)
562                                              sensors_interval);
563     }
564     GNUNET_CONFIGURATION_write (sensor_cfg, dst_path);
565     GNUNET_CONFIGURATION_destroy (sensor_cfg);
566   }
567   GNUNET_free (dst_path);
568   return GNUNET_OK;
569 }
570
571
572 /**
573  * Load sensor definitions and rewrite them to tmp location.
574  * Add collection point peer id and change running interval if needed.
575  */
576 static void
577 rewrite_sensors ()
578 {
579   GNUNET_assert (GNUNET_YES ==
580                  GNUNET_DISK_directory_test (sensor_src_dir, GNUNET_YES));
581   GNUNET_assert (GNUNET_OK == GNUNET_DISK_directory_create (sensor_dst_dir));
582   GNUNET_DISK_directory_scan (sensor_src_dir, &sensor_dir_scanner, NULL);
583 }
584
585
586 /**
587  * Callback to be called when dashboard service is started
588  *
589  * @param cls the callback closure from functions generating an operation
590  * @param op the operation that has been finished
591  * @param emsg error message in case the operation has failed; will be NULL if
592  *          operation has executed successfully.
593  */
594 static void
595 dashboard_started (void *cls, struct GNUNET_TESTBED_Operation *op,
596                    const char *emsg)
597 {
598   if (NULL != emsg)
599   {
600     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ERROR: %s.\n", emsg);
601     GNUNET_assert (0);
602   }
603   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Dashboard service started.\n");
604   GNUNET_TESTBED_operation_done (op);
605   dashboard_service_started = GNUNET_YES;
606 }
607
608
609 /**
610  * Function called by PEERSTORE for each matching record.
611  *
612  * @param cls closure
613  * @param record peerstore record information
614  * @param emsg error message, or NULL if no errors
615  * @return #GNUNET_YES to continue iterating, #GNUNET_NO to stop
616  */
617 static int
618 peerstore_watch_cb (void *cls, struct GNUNET_PEERSTORE_Record *record,
619                     char *emsg)
620 {
621   struct PeerInfo *peer = cls;
622   struct GNUNET_SENSOR_DashboardAnomalyEntry *anomaly;
623
624   if (NULL != emsg)
625   {
626     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ERROR: %s.\n", emsg);
627     GNUNET_assert (0);
628   }
629   GNUNET_assert (record->value_size ==
630                  sizeof (struct GNUNET_SENSOR_DashboardAnomalyEntry));
631   anomaly = record->value;
632   GNUNET_assert (0 ==
633                  GNUNET_CRYPTO_cmp_peer_identity (&peer->peer_id,
634                                                   record->peer));
635   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
636               "Anomaly report:{'peerid': '%s'," "'peer': %d," "'sensor': '%s',"
637               "'anomalous': %d," "'neighbors': %f}\n",
638               GNUNET_i2s (&peer->peer_id), peer->index, record->key,
639               anomaly->anomalous, anomaly->anomalous_neighbors);
640   return GNUNET_YES;
641 }
642
643
644 /**
645  * Callback to be called when peerstore service connect operation is completed
646  *
647  * @param cls the callback closure from functions generating an operation
648  * @param op the operation that has been finished
649  * @param ca_result the service handle returned from GNUNET_TESTBED_ConnectAdapter()
650  * @param emsg error message in case the operation has failed; will be NULL if
651  *          operation has executed successfully.
652  */
653 static void
654 peerstore_connect_cb (void *cls, struct GNUNET_TESTBED_Operation *op,
655                       void *ca_result, const char *emsg)
656 {
657   int i;
658   int j;
659   struct PeerInfo *peer;
660
661   if (NULL != emsg)
662   {
663     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ERROR: %s.\n", emsg);
664     GNUNET_assert (0);
665   }
666   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connected to peerstore service.\n");
667   /* Watch for anomaly reports from other peers */
668   for (i = 0; i < num_peers; i++)
669   {
670     peer = &all_peers_info[i];
671     for (j = 0; j < sensor_names_size; j++)
672     {
673       GNUNET_PEERSTORE_watch (peerstore, "sensordashboard-anomalies",
674                               &peer->peer_id, sensor_names[j],
675                               &peerstore_watch_cb, peer);
676     }
677   }
678 }
679
680
681 /**
682  * Adapter function called to establish a connection to peerstore service.
683  *
684  * @param cls closure
685  * @param cfg configuration of the peer to connect to; will be available until
686  *          GNUNET_TESTBED_operation_done() is called on the operation returned
687  *          from GNUNET_TESTBED_service_connect()
688  * @return service handle to return in 'op_result', NULL on error
689  */
690 static void *
691 peerstore_connect_adapter (void *cls,
692                            const struct GNUNET_CONFIGURATION_Handle *cfg)
693 {
694   peerstore = GNUNET_PEERSTORE_connect (cfg);
695   GNUNET_assert (NULL != peerstore);
696   return peerstore;
697 }
698
699
700 /**
701  * Adapter function called to destroy a connection to peerstore service.
702  *
703  * @param cls closure
704  * @param op_result service handle returned from the connect adapter
705  */
706 static void
707 peerstore_disconnect_adapter (void *cls, void *op_result)
708 {
709   GNUNET_PEERSTORE_disconnect (peerstore, GNUNET_NO);
710   peerstore = NULL;
711   peerstore_op = NULL;
712 }
713
714
715 /**
716  * Prompty the user to reconnect two peers
717  */
718 static void
719 prompt_peer_reconnection (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
720 {
721   int p1;
722   int p2;
723   char line[10];
724
725   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
726               "Connect peers (e.g. '0,2') or empty line to execute:\n");
727   if (NULL == fgets (line, sizeof (line), stdin) || 1 == strlen (line))
728   {
729     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Continuing.\n");
730     return;
731   }
732   if (2 != sscanf (line, "%d,%d", &p1, &p2) || p1 >= num_peers ||
733       p2 >= num_peers || p1 < 0 || p2 < 0 || p1 == p2)
734   {
735     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Invalid input.\n");
736     prompt_peer_reconnection (NULL, NULL);
737     return;
738   }
739   connect_peers (&all_peers_info[p1], &all_peers_info[p2]);
740   prompt_peer_reconnection (NULL, NULL);
741 }
742
743
744 /**
745  * Prompt the user to disconnect two peers
746  */
747 static void
748 prompt_peer_disconnection ()
749 {
750   int p1;
751   int p2;
752   char line[10];
753
754   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
755               "Disconnect peers (e.g. '0,2') or empty line to execute:\n");
756   if (NULL == fgets (line, sizeof (line), stdin) || 1 == strlen (line))
757   {
758     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Will prompt for reconnection in 1 min.\n");
759     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 1) ,&prompt_peer_reconnection, NULL);
760     return;
761   }
762   if (2 != sscanf (line, "%d,%d", &p1, &p2) || p1 >= num_peers ||
763       p2 >= num_peers || p1 < 0 || p2 < 0 || p1 == p2)
764   {
765     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Invalid input.\n");
766     prompt_peer_disconnection ();
767     return;
768   }
769   disconnect_peers (&all_peers_info[p1], &all_peers_info[p2]);
770   prompt_peer_disconnection ();
771 }
772
773
774 /**
775  * This function is called after the estimated training period is over.
776  */
777 static void
778 simulate_anomalies (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
779 {
780   delayed_task = GNUNET_SCHEDULER_NO_TASK;
781   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
782               "Training period over, simulating anomalies now.\n");
783   prompt_peer_disconnection ();
784 }
785
786
787 /**
788  * This function is called after a delay which ensures that all peers are
789  * properly initialized
790  */
791 static void
792 peers_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
793 {
794   unsigned long long int training_points;
795   struct GNUNET_TIME_Relative training_period;
796
797   delayed_task = GNUNET_SCHEDULER_NO_TASK;
798   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "All peers are ready.\n");
799   GNUNET_assert (GNUNET_OK ==
800                  GNUNET_CONFIGURATION_get_value_number (cfg,
801                                                         "sensor-model-gaussian",
802                                                         "TRAINING_WINDOW",
803                                                         &training_points));
804   training_period =
805       GNUNET_TIME_relative_multiply (GNUNET_TIME_relative_multiply
806                                      (GNUNET_TIME_UNIT_SECONDS,
807                                       (sensors_interval ==
808                                        0) ? 60 : sensors_interval),
809                                      training_points);
810   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
811               "Sleeping for a training period of %s.\n",
812               GNUNET_STRINGS_relative_time_to_string (training_period,
813                                                       GNUNET_NO));
814   delayed_task =
815       GNUNET_SCHEDULER_add_delayed (training_period, &simulate_anomalies, NULL);
816 }
817
818
819 /**
820  * Callback to be called when sensor service is started
821  *
822  * @param cls the callback closure from functions generating an operation
823  * @param op the operation that has been finished
824  * @param emsg error message in case the operation has failed; will be NULL if
825  *          operation has executed successfully.
826  */
827 static void
828 sensor_service_started (void *cls, struct GNUNET_TESTBED_Operation *op,
829                         const char *emsg)
830 {
831   struct PeerInfo *peer = cls;
832
833   if (NULL != emsg)
834   {
835     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ERROR: %s.\n", emsg);
836     GNUNET_assert (0);
837   }
838   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sensor service started on peer `%s'.\n",
839               GNUNET_i2s (&peer->peer_id));
840   GNUNET_TESTBED_operation_done (op);
841   sensor_services_started++;
842   if (sensor_services_started == num_peers)
843   {
844     delayed_task =
845         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
846                                       (PEER_STARTUP_TIME, num_peers),
847                                       &peers_ready, NULL);
848   }
849 }
850
851
852 /**
853  * Callback to be called when the requested peer information is available
854  *
855  * @param cb_cls the closure from GNUNET_TETSBED_peer_get_information()
856  * @param op the operation this callback corresponds to
857  * @param pinfo the result; will be NULL if the operation has failed
858  * @param emsg error message if the operation has failed; will be NULL if the
859  *          operation is successfull
860  */
861 static void
862 peer_info_cb (void *cb_cls, struct GNUNET_TESTBED_Operation *op,
863               const struct GNUNET_TESTBED_PeerInformation *pinfo,
864               const char *emsg)
865 {
866   struct GNUNET_TESTBED_Peer *testbed_peer = cb_cls;
867   struct PeerInfo *peer = &all_peers_info[peers_known];
868
869   if (NULL != emsg)
870   {
871     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ERROR: %s.\n", emsg);
872     GNUNET_assert (0);
873   }
874   peer->testbed_peer = testbed_peer;
875   GNUNET_CRYPTO_get_peer_identity (pinfo->result.cfg, &peer->peer_id);
876   peer->index = peers_known;
877   peers_known++;
878   if (1 == peers_known)         /* First peer is collection point */
879   {
880     /* Rewrite sensors */
881     rewrite_sensors ();
882     /* Start dashboard */
883     GNUNET_TESTBED_peer_manage_service (NULL, testbed_peer, "sensordashboard",
884                                         &dashboard_started, NULL, 1);
885   }
886   /* Start sensor service on every peer */
887   GNUNET_TESTBED_peer_manage_service (NULL, testbed_peer, "sensor",
888                                       &sensor_service_started, peer, 1);
889   if (num_peers == peers_known) /* Last peer */
890   {
891     /* Connect to peerstore on first peer (collection point) */
892     peerstore_op =
893         GNUNET_TESTBED_service_connect (NULL, all_peers_info[0].testbed_peer,
894                                         "peerstore", &peerstore_connect_cb,
895                                         NULL, &peerstore_connect_adapter,
896                                         &peerstore_disconnect_adapter, NULL);
897   }
898   GNUNET_TESTBED_operation_done (op);
899 }
900
901
902 /**
903  * Signature of a main function for a testcase.
904  *
905  * @param cls closure
906  * @param h the run handle
907  * @param num number of peers in 'peers'
908  * @param peers handle to peers run in the testbed.  NULL upon timeout (see
909  *          GNUNET_TESTBED_test_run()).
910  * @param links_succeeded the number of overlay link connection attempts that
911  *          succeeded
912  * @param links_failed the number of overlay link connection attempts that
913  *          failed
914  * @see GNUNET_TESTBED_test_run()
915  */
916 static void
917 test_master (void *cls, struct GNUNET_TESTBED_RunHandle *h, unsigned int num,
918              struct GNUNET_TESTBED_Peer **peers, unsigned int links_succeeded,
919              unsigned int links_failed)
920 {
921   int i;
922
923   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
924               "%d peers started. %d links succeeded. %d links failed.\n",
925               num_peers, links_succeeded, links_failed);
926   GNUNET_assert (num == num_peers);
927   GNUNET_assert (0 == links_failed);
928   /* Collect peer information */
929   all_peers_info = GNUNET_new_array (num_peers, struct PeerInfo);
930
931   for (i = 0; i < num_peers; i++)
932   {
933     GNUNET_TESTBED_peer_get_information (peers[i],
934                                          GNUNET_TESTBED_PIT_CONFIGURATION,
935                                          &peer_info_cb, peers[i]);
936   }
937 }
938
939
940 /**
941  * Verify that the user passed correct CL args
942  *
943  * @return #GNUNET_OK if arguments are valid, #GNUNET_SYSERR otherwise
944  */
945 static int
946 verify_args ()
947 {
948   if (num_peers < 2)
949   {
950     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
951                 _
952                 ("Invalid or missing number of peers. Set at least 2 peers.\n"));
953     return GNUNET_SYSERR;
954   }
955   if (NULL == topology_file ||
956       GNUNET_YES != GNUNET_DISK_file_test (topology_file))
957   {
958     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
959                 _("Missing or invalid topology file.\n"));
960     return GNUNET_SYSERR;
961   }
962   return GNUNET_OK;
963 }
964
965
966 /**
967  * Actual main function.
968  *
969  * @param cls unused
970  * @param args remaining args, unused
971  * @param cfgfile name of the configuration
972  * @param cfg configuration handle
973  */
974 static void
975 run (void *cls, char *const *args, const char *cf,
976      const struct GNUNET_CONFIGURATION_Handle *c)
977 {
978   if (GNUNET_OK != verify_args ())
979   {
980     do_shutdown (NULL, NULL);
981     return;
982   }
983   cfg = GNUNET_CONFIGURATION_create ();
984   GNUNET_assert (GNUNET_OK == GNUNET_CONFIGURATION_load (cfg, cfg_filename));
985   GNUNET_CONFIGURATION_set_value_string ((struct GNUNET_CONFIGURATION_Handle *)
986                                          cfg, "TESTBED",
987                                          "OVERLAY_TOPOLOGY_FILE",
988                                          topology_file);
989   shutdown_task =
990       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &do_shutdown,
991                                     NULL);
992   GNUNET_TESTBED_run (NULL, cfg, num_peers, 0, NULL, NULL, &test_master, NULL);
993 }
994
995
996 /**
997  * Main function.
998  *
999  * @return 0 on success
1000  */
1001 int
1002 main (int argc, char *const *argv)
1003 {
1004   static struct GNUNET_GETOPT_CommandLineOption options[] = {
1005     {'p', "peers", "COUNT", gettext_noop ("Number of peers to run"), GNUNET_YES,
1006      &GNUNET_GETOPT_set_uint, &num_peers},
1007     {'t', "topology-file", "FILEPATH", gettext_noop ("Path to topology file"),
1008      GNUNET_YES, &GNUNET_GETOPT_set_filename, &topology_file},
1009     {'i', "sensors-interval", "INTERVAL",
1010      gettext_noop ("Change the interval of running sensors to given value"),
1011      GNUNET_YES, &GNUNET_GETOPT_set_uint, &sensors_interval},
1012     GNUNET_GETOPT_OPTION_END
1013   };
1014
1015   return (GNUNET_OK ==
1016           GNUNET_PROGRAM_run (argc, argv, "gnunet-sensor-profiler",
1017                               gettext_noop ("Profiler for sensor service"),
1018                               options, &run, NULL)) ? 0 : 1;
1019 }
1020
1021 /* end of gnunet-sensor-profiler.c */