sensor: towards profiler
[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
33 /**
34  * Time to wait for the peer to startup completely
35  */
36 #define PEER_STARTUP_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
37
38 /**
39  * Information about a single peer
40  */
41 struct PeerInfo
42 {
43
44   /**
45    * Peer Identity
46    */
47   struct GNUNET_PeerIdentity peer_id;
48
49   /**
50    * Testbed peer handle
51    */
52   struct GNUNET_TESTBED_Peer *testbed_peer;
53
54 };
55
56
57 /**
58  * Name of the configuration file used
59  */
60 static const char *cfg_filename = "gnunet-sensor-profiler.conf";
61
62 /**
63  * Directory to read sensor definitions from
64  */
65 static const char *sensor_src_dir = "sensors";
66
67 /**
68  * Directory to write new sensor definitions to
69  */
70 static const char *sensor_dst_dir = "/tmp/gnunet-sensor-profiler";
71
72 /**
73  * GNUnet configuration
74  */
75 struct GNUNET_CONFIGURATION_Handle *cfg;
76
77 /**
78  * Return value of the program
79  */
80 static int ok = 1;
81
82 /**
83  * Number of peers to run (Option -p)
84  */
85 static unsigned int num_peers = 0;
86
87 /**
88  * Set sensors running interval to this value (Option -i)
89  */
90 static unsigned int sensors_interval = 0;
91
92 /**
93  * Path to topology file (Option -t)
94  */
95 static char *topology_file;
96
97 /**
98  * Array of peer info for all peers
99  */
100 static struct PeerInfo *all_peers_info;
101
102 /**
103  * Number of peers that we already collected and start their info
104  */
105 static int peers_known = 0;
106
107 /**
108  * TESTBED operation connecting us to peerstore service on collection point
109  */
110 static struct GNUNET_TESTBED_Operation *peerstore_op;
111
112 /**
113  * Handle to peerstore service on collection point
114  */
115 static struct GNUNET_PEERSTORE_Handle *peerstore;
116
117 /**
118  * Dashboard service on collection point started?
119  */
120 static int dashboard_service_started = GNUNET_NO;
121
122 /**
123  * Number of peers started the sensor service successfully
124  */
125 static int sensor_services_started = 0;
126
127 /**
128  * Array of sensor names to be used for watching peerstore records
129  */
130 static char **sensor_names;
131
132 /**
133  * Size of 'sensor_names' array
134  */
135 static unsigned int sensor_names_size = 0;
136
137
138 /**
139  * Copy directory recursively
140  *
141  * @param src Path to source directory
142  * @param dst Destination directory, will be created if it does not exist
143  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
144  */
145 static int
146 copy_dir (const char *src, const char *dst);
147
148
149 /**
150  * Do clean up and shutdown scheduler
151  */
152 static void
153 do_shutdown (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
154 {
155   int i;
156
157   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Shutting down.\n");
158   if (NULL != cfg)
159   {
160     GNUNET_CONFIGURATION_destroy (cfg);
161     cfg = NULL;
162   }
163   if (NULL != sensor_names)
164   {
165     for (i = 0; i < sensor_names_size; i++)
166       GNUNET_free (sensor_names[i]);
167     GNUNET_array_grow (sensor_names, sensor_names_size, 0);
168   }
169   if (NULL != peerstore_op)
170   {
171     GNUNET_TESTBED_operation_done (peerstore_op);
172     peerstore_op = NULL;
173   }
174   if (NULL != all_peers_info)
175   {
176     GNUNET_free (all_peers_info);
177     all_peers_info = NULL;
178   }
179   GNUNET_SCHEDULER_shutdown ();
180 }
181
182
183 /**
184  * Function called with each file/folder inside a directory that is being copied.
185  *
186  * @param cls closure, destination directory
187  * @param filename complete filename (absolute path)
188  * @return #GNUNET_OK to continue to iterate.
189  *         #GNUNET_SYSERR to abort iteration with error
190  */
191 static int
192 copy_dir_scanner (void *cls, const char *filename)
193 {
194   char *dst_dir = cls;
195   char *dst;
196   int copy_result;
197
198   GNUNET_asprintf (&dst, "%s%s%s", dst_dir, DIR_SEPARATOR_STR,
199                    GNUNET_STRINGS_get_short_name (filename));
200   if (GNUNET_YES == GNUNET_DISK_directory_test (filename, GNUNET_YES))
201     copy_result = copy_dir (filename, dst);
202   else
203   {
204     if (GNUNET_YES == GNUNET_DISK_file_test (dst))
205       GNUNET_DISK_directory_remove (dst);
206     copy_result = GNUNET_DISK_file_copy (filename, dst);
207   }
208   GNUNET_free (dst);
209   return copy_result;
210 }
211
212
213 /**
214  * Copy directory recursively
215  *
216  * @param src Path to source directory
217  * @param dst Destination directory, will be created if it does not exist
218  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
219  */
220 static int
221 copy_dir (const char *src, const char *dst)
222 {
223   if (GNUNET_YES != GNUNET_DISK_directory_test (src, GNUNET_YES))
224     return GNUNET_SYSERR;
225   if (GNUNET_OK != GNUNET_DISK_directory_create (dst))
226     return GNUNET_SYSERR;
227   if (GNUNET_SYSERR ==
228       GNUNET_DISK_directory_scan (src, &copy_dir_scanner, (char *) dst))
229     return GNUNET_SYSERR;
230   return GNUNET_OK;
231 }
232
233
234 /**
235  * Function called with each file/folder inside source sensor directory.
236  *
237  * @param cls closure (unused)
238  * @param filename complete filename (absolute path)
239  * @return #GNUNET_OK to continue to iterate.
240  */
241 static int
242 sensor_dir_scanner (void *cls, const char *filename)
243 {
244   const char *file_basename;
245   char *dst_path;
246   struct GNUNET_CONFIGURATION_Handle *sensor_cfg;
247   char *sensor_name;
248
249   file_basename = GNUNET_STRINGS_get_short_name (filename);
250   GNUNET_asprintf (&dst_path, "%s%s%s", sensor_dst_dir, DIR_SEPARATOR_STR,
251                    file_basename);
252   if (GNUNET_YES == GNUNET_DISK_directory_test (filename, GNUNET_NO))
253   {
254     GNUNET_assert (GNUNET_OK == copy_dir (filename, dst_path));
255   }
256   else
257   {
258     sensor_name = GNUNET_strdup (file_basename);
259     GNUNET_array_append (sensor_names, sensor_names_size, sensor_name);
260     sensor_cfg = GNUNET_CONFIGURATION_create ();
261     GNUNET_assert (GNUNET_OK ==
262                    GNUNET_CONFIGURATION_parse (sensor_cfg, filename));
263     GNUNET_CONFIGURATION_set_value_string (sensor_cfg, file_basename,
264                                            "COLLECTION_POINT",
265                                            GNUNET_i2s_full (&all_peers_info
266                                                             [0].peer_id));
267     if (sensors_interval > 0)
268     {
269       GNUNET_CONFIGURATION_set_value_number (sensor_cfg, file_basename,
270                                              "INTERVAL",
271                                              (unsigned long long int)
272                                              sensors_interval);
273     }
274     GNUNET_CONFIGURATION_write (sensor_cfg, dst_path);
275     GNUNET_CONFIGURATION_destroy (sensor_cfg);
276   }
277   GNUNET_free (dst_path);
278   return GNUNET_OK;
279 }
280
281
282 /**
283  * Load sensor definitions and rewrite them to tmp location.
284  * Add collection point peer id and change running interval if needed.
285  */
286 static void
287 rewrite_sensors ()
288 {
289   GNUNET_assert (GNUNET_YES ==
290                  GNUNET_DISK_directory_test (sensor_src_dir, GNUNET_YES));
291   GNUNET_assert (GNUNET_OK == GNUNET_DISK_directory_create (sensor_dst_dir));
292   GNUNET_DISK_directory_scan (sensor_src_dir, &sensor_dir_scanner, NULL);
293 }
294
295
296 /**
297  * Callback to be called when dashboard service is started
298  *
299  * @param cls the callback closure from functions generating an operation
300  * @param op the operation that has been finished
301  * @param emsg error message in case the operation has failed; will be NULL if
302  *          operation has executed successfully.
303  */
304 static void
305 dashboard_started (void *cls, struct GNUNET_TESTBED_Operation *op,
306                    const char *emsg)
307 {
308   if (NULL != emsg)
309   {
310     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ERROR: %s.\n", emsg);
311     GNUNET_assert (0);
312   }
313   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Dashboard service started.\n");
314   GNUNET_TESTBED_operation_done (op);
315   dashboard_service_started = GNUNET_YES;
316 }
317
318
319 /**
320  * Function called by PEERSTORE for each matching record.
321  *
322  * @param cls closure
323  * @param record peerstore record information
324  * @param emsg error message, or NULL if no errors
325  * @return #GNUNET_YES to continue iterating, #GNUNET_NO to stop
326  */
327 static int
328 peerstore_watch_cb (void *cls, struct GNUNET_PEERSTORE_Record *record,
329                     char *emsg)
330 {
331   struct PeerInfo *peer = cls;
332   struct GNUNET_SENSOR_DashboardAnomalyEntry *anomaly;
333
334   if (NULL != emsg)
335   {
336     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ERROR: %s.\n", emsg);
337     GNUNET_assert (0);
338   }
339   GNUNET_assert (record->value_size ==
340                  sizeof (struct GNUNET_SENSOR_DashboardAnomalyEntry));
341   anomaly = record->value;
342   GNUNET_assert (0 ==
343                  GNUNET_CRYPTO_cmp_peer_identity (&peer->peer_id,
344                                                   record->peer));
345   printf ("Anomaly report:\n" "  Peer: `%s'\n" "  Sensor: `%s'\n"
346           "  Anomalous: `%d'\n" "  Anomalous neighbors: %f.\n\n",
347           GNUNET_i2s (&peer->peer_id), record->key, anomaly->anomalous,
348           anomaly->anomalous_neighbors);
349   return GNUNET_YES;
350 }
351
352
353 /**
354  * Callback to be called when peerstore service connect operation is completed
355  *
356  * @param cls the callback closure from functions generating an operation
357  * @param op the operation that has been finished
358  * @param ca_result the service handle returned from GNUNET_TESTBED_ConnectAdapter()
359  * @param emsg error message in case the operation has failed; will be NULL if
360  *          operation has executed successfully.
361  */
362 static void
363 peerstore_connect_cb (void *cls, struct GNUNET_TESTBED_Operation *op,
364                       void *ca_result, const char *emsg)
365 {
366   int i;
367   int j;
368   struct PeerInfo *peer;
369
370   if (NULL != emsg)
371   {
372     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ERROR: %s.\n", emsg);
373     GNUNET_assert (0);
374   }
375   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connected to peerstore service.\n");
376   /* Watch for anomaly reports from other peers */
377   for (i = 0; i < num_peers; i++)
378   {
379     peer = &all_peers_info[i];
380     for (j = 0; j < sensor_names_size; j++)
381     {
382       GNUNET_PEERSTORE_watch (peerstore, "sensordashboard-anomalies",
383                               &peer->peer_id, sensor_names[j],
384                               &peerstore_watch_cb, peer);
385     }
386   }
387 }
388
389
390 /**
391  * Adapter function called to establish a connection to peerstore service.
392  *
393  * @param cls closure
394  * @param cfg configuration of the peer to connect to; will be available until
395  *          GNUNET_TESTBED_operation_done() is called on the operation returned
396  *          from GNUNET_TESTBED_service_connect()
397  * @return service handle to return in 'op_result', NULL on error
398  */
399 static void *
400 peerstore_connect_adapter (void *cls,
401                            const struct GNUNET_CONFIGURATION_Handle *cfg)
402 {
403   peerstore = GNUNET_PEERSTORE_connect (cfg);
404   GNUNET_assert (NULL != peerstore);
405   return peerstore;
406 }
407
408
409 /**
410  * Adapter function called to destroy a connection to peerstore service.
411  *
412  * @param cls closure
413  * @param op_result service handle returned from the connect adapter
414  */
415 static void
416 peerstore_disconnect_adapter (void *cls, void *op_result)
417 {
418   GNUNET_PEERSTORE_disconnect (peerstore, GNUNET_NO);
419   peerstore = NULL;
420   peerstore_op = NULL;
421 }
422
423
424 /**
425  * This function is called after a delay which ensures that all peers are
426  * properly initialized
427  */
428 static void
429 peers_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
430 {
431   unsigned long long int training_points;
432   struct GNUNET_TIME_Relative training_period;
433
434   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "All peers are ready.\n");
435   GNUNET_assert (GNUNET_OK ==
436                  GNUNET_CONFIGURATION_get_value_number (cfg,
437                                                         "sensor-model-gaussian",
438                                                         "TRAINING_WINDOW",
439                                                         &training_points));
440   training_period =
441       GNUNET_TIME_relative_multiply (GNUNET_TIME_relative_multiply
442                                      (GNUNET_TIME_UNIT_SECONDS,
443                                       (sensors_interval ==
444                                        0) ? 60 : sensors_interval),
445                                      training_points);
446   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
447               "Sleeping for a training period of %s.\n",
448               GNUNET_STRINGS_relative_time_to_string (training_period,
449                                                       GNUNET_NO));
450   //TODO
451 }
452
453
454 /**
455  * Callback to be called when sensor service is started
456  *
457  * @param cls the callback closure from functions generating an operation
458  * @param op the operation that has been finished
459  * @param emsg error message in case the operation has failed; will be NULL if
460  *          operation has executed successfully.
461  */
462 static void
463 sensor_service_started (void *cls, struct GNUNET_TESTBED_Operation *op,
464                         const char *emsg)
465 {
466   struct PeerInfo *peer = cls;
467
468   if (NULL != emsg)
469   {
470     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ERROR: %s.\n", emsg);
471     GNUNET_assert (0);
472   }
473   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sensor service started on peer `%s'.\n",
474               GNUNET_i2s (&peer->peer_id));
475   GNUNET_TESTBED_operation_done (op);
476   sensor_services_started++;
477   if (sensor_services_started == num_peers)
478   {
479     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
480                                   (PEER_STARTUP_TIME, num_peers), &peers_ready,
481                                   NULL);
482   }
483 }
484
485
486 /**
487  * Callback to be called when the requested peer information is available
488  *
489  * @param cb_cls the closure from GNUNET_TETSBED_peer_get_information()
490  * @param op the operation this callback corresponds to
491  * @param pinfo the result; will be NULL if the operation has failed
492  * @param emsg error message if the operation has failed; will be NULL if the
493  *          operation is successfull
494  */
495 static void
496 peer_info_cb (void *cb_cls, struct GNUNET_TESTBED_Operation *op,
497               const struct GNUNET_TESTBED_PeerInformation *pinfo,
498               const char *emsg)
499 {
500   struct GNUNET_TESTBED_Peer *testbed_peer = cb_cls;
501   struct PeerInfo *peer = &all_peers_info[peers_known];
502
503   if (NULL != emsg)
504   {
505     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "ERROR: %s.\n", emsg);
506     GNUNET_assert (0);
507   }
508   peer->testbed_peer = testbed_peer;
509   GNUNET_CRYPTO_get_peer_identity (pinfo->result.cfg, &peer->peer_id);
510   peers_known++;
511   if (1 == peers_known)         /* First peer is collection point */
512   {
513     /* Rewrite sensors */
514     rewrite_sensors ();
515     /* Start dashboard */
516     GNUNET_TESTBED_peer_manage_service (NULL, testbed_peer, "sensordashboard",
517                                         &dashboard_started, NULL, 1);
518   }
519   /* Start sensor service on every peer */
520   GNUNET_TESTBED_peer_manage_service (NULL, testbed_peer, "sensor",
521                                       &sensor_service_started, peer, 1);
522   if (num_peers == peers_known) /* Last peer */
523   {
524     /* Connect to peerstore on first peer (collection point) */
525     peerstore_op =
526         GNUNET_TESTBED_service_connect (NULL, all_peers_info[0].testbed_peer,
527                                         "peerstore", &peerstore_connect_cb,
528                                         NULL, &peerstore_connect_adapter,
529                                         &peerstore_disconnect_adapter, NULL);
530   }
531   GNUNET_TESTBED_operation_done (op);
532 }
533
534
535 /**
536  * Signature of a main function for a testcase.
537  *
538  * @param cls closure
539  * @param h the run handle
540  * @param num number of peers in 'peers'
541  * @param peers handle to peers run in the testbed.  NULL upon timeout (see
542  *          GNUNET_TESTBED_test_run()).
543  * @param links_succeeded the number of overlay link connection attempts that
544  *          succeeded
545  * @param links_failed the number of overlay link connection attempts that
546  *          failed
547  * @see GNUNET_TESTBED_test_run()
548  */
549 static void
550 test_master (void *cls, struct GNUNET_TESTBED_RunHandle *h, unsigned int num,
551              struct GNUNET_TESTBED_Peer **peers, unsigned int links_succeeded,
552              unsigned int links_failed)
553 {
554   int i;
555
556   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
557               "%d peers started. %d links succeeded. %d links failed.\n",
558               num_peers, links_succeeded, links_failed);
559   GNUNET_assert (num == num_peers);
560   GNUNET_assert (0 == links_failed);
561   /* Collect peer information */
562   all_peers_info = GNUNET_new_array (num_peers, struct PeerInfo);
563
564   for (i = 0; i < num_peers; i++)
565   {
566     GNUNET_TESTBED_peer_get_information (peers[i],
567                                          GNUNET_TESTBED_PIT_CONFIGURATION,
568                                          &peer_info_cb, peers[i]);
569   }
570 }
571
572
573 /**
574  * Verify that the user passed correct CL args
575  *
576  * @return #GNUNET_OK if arguments are valid, #GNUNET_SYSERR otherwise
577  */
578 static int
579 verify_args ()
580 {
581   if (num_peers < 3)
582   {
583     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
584                 _
585                 ("Invalid or missing number of peers. Set at least 3 peers.\n"));
586     return GNUNET_SYSERR;
587   }
588   if (NULL == topology_file ||
589       GNUNET_YES != GNUNET_DISK_file_test (topology_file))
590   {
591     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
592                 _("Missing or invalid topology file.\n"));
593     return GNUNET_SYSERR;
594   }
595   return GNUNET_OK;
596 }
597
598
599 /**
600  * Actual main function.
601  *
602  * @param cls unused
603  * @param args remaining args, unused
604  * @param cfgfile name of the configuration
605  * @param cfg configuration handle
606  */
607 static void
608 run (void *cls, char *const *args, const char *cf,
609      const struct GNUNET_CONFIGURATION_Handle *c)
610 {
611   if (GNUNET_OK != verify_args ())
612   {
613     do_shutdown (NULL, NULL);
614     return;
615   }
616   cfg = GNUNET_CONFIGURATION_create ();
617   GNUNET_assert (GNUNET_OK == GNUNET_CONFIGURATION_load (cfg, cfg_filename));
618   GNUNET_CONFIGURATION_set_value_string ((struct GNUNET_CONFIGURATION_Handle *)
619                                          cfg, "TESTBED",
620                                          "OVERLAY_TOPOLOGY_FILE",
621                                          topology_file);
622   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &do_shutdown,
623                                 NULL);
624   GNUNET_TESTBED_run (NULL, cfg, num_peers, 0, NULL, NULL, &test_master, NULL);
625 }
626
627
628 /**
629  * Main function.
630  *
631  * @return 0 on success
632  */
633 int
634 main (int argc, char *const *argv)
635 {
636   static struct GNUNET_GETOPT_CommandLineOption options[] = {
637     {'p', "peers", "COUNT", gettext_noop ("Number of peers to run"), GNUNET_YES,
638      &GNUNET_GETOPT_set_uint, &num_peers},
639     {'t', "topology-file", "FILEPATH", gettext_noop ("Path to topology file"),
640      GNUNET_YES, &GNUNET_GETOPT_set_filename, &topology_file},
641     {'i', "sensors-interval", "INTERVAL",
642      gettext_noop ("Change the interval or running sensors to given value"),
643      GNUNET_YES, &GNUNET_GETOPT_set_uint, &sensors_interval},
644     GNUNET_GETOPT_OPTION_END
645   };
646
647   return (GNUNET_OK ==
648           GNUNET_PROGRAM_run (argc, argv, "gnunet-sensor-profiler",
649                               gettext_noop ("Profiler for sensor service"),
650                               options, &run, NULL)) ? ok : 1;
651 }
652
653 /* end of gnunet-sensor-profiler.c */