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