few fixes
[oweals/gnunet.git] / src / sensor / gnunet-service-sensor.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-service-sensor.c
23  * @brief sensor service implementation
24  * @author Omar Tarabai
25  */
26 #include <inttypes.h>
27 #include "platform.h"
28 #include "gnunet_util_lib.h"
29 #include "sensor.h"
30 #include "gnunet_statistics_service.h"
31
32 /**
33  * Minimum sensor execution interval (in seconds)
34  */
35 #define MIN_INTERVAL 30
36
37 /**
38  * Structure containing sensor definition
39  */
40 struct SensorInfo
41 {
42
43   /*
44    * Sensor name
45    */
46   char *name;
47
48   /*
49    * Path to definition file
50    */
51   char *def_file;
52
53   /*
54    * First part of version number
55    */
56   uint16_t version_major;
57
58   /*
59    * Second part of version number
60    */
61   uint16_t version_minor;
62
63   /*
64    * Sensor description
65    */
66   char *description;
67
68   /*
69    * Sensor currently enabled
70    */
71   int enabled;
72
73   /*
74    * Category under which the sensor falls (e.g. tcp, datastore)
75    */
76   char *category;
77
78   /*
79    * When does the sensor become active
80    */
81   struct GNUNET_TIME_Absolute *start_time;
82
83   /*
84    * When does the sensor expire
85    */
86   struct GNUNET_TIME_Absolute *end_time;
87
88   /*
89    * Time interval to collect sensor information (e.g. every 1 min)
90    */
91   struct GNUNET_TIME_Relative interval;
92
93   /*
94    * Lifetime of an information sample after which it is deleted from storage
95    */
96   struct GNUNET_TIME_Relative lifetime;
97
98   /*
99    * A set of required peer capabilities for the sensor to collect meaningful information (e.g. ipv6)
100    */
101   char *capabilities;
102
103   /*
104    * Either "gnunet-statistics" or external "process"
105    */
106   char *source;
107
108   /*
109    * Name of the GNUnet service that is the source for the gnunet-statistics entry
110    */
111   char *gnunet_stat_service;
112
113   /*
114    * Name of the gnunet-statistics entry
115    */
116   char *gnunet_stat_name;
117
118   /**
119    * Handle to statistics get request (OR GNUNET_SCHEDULER_NO_TASK)
120    */
121   struct GNUNET_STATISTICS_GetHandle *gnunet_stat_get_handle;
122
123   /*
124    * Name of the external process to be executed
125    */
126   char *ext_process;
127
128   /*
129    * Arguments to be passed to the external process
130    */
131   char *ext_args;
132
133   /*
134    * The output datatype to be expected
135    */
136   char *expected_datatype;
137
138   /*
139    * Peer-identity of peer running collection point
140    */
141   struct GNUNET_PeerIdentity *collection_point;
142
143   /*
144    * Time interval to send sensor information to collection point (e.g. every 30 mins)
145    */
146   struct GNUNET_TIME_Relative *collection_interval;
147
148   /*
149    * Flag specifying if value is to be communicated to the p2p network
150    */
151   int p2p_report;
152
153   /*
154    * Time interval to communicate value to the p2p network
155    */
156   struct GNUNET_TIME_Relative *p2p_interval;
157
158   /*
159    * Execution task (OR GNUNET_SCHEDULER_NO_TASK)
160    */
161   GNUNET_SCHEDULER_TaskIdentifier execution_task;
162
163   /*
164    * Is the sensor being executed
165    */
166   int running;
167
168 };
169
170 /**
171  * Our configuration.
172  */
173 static const struct GNUNET_CONFIGURATION_Handle *cfg;
174
175 /**
176  * Hashmap of loaded sensor definitions
177  */
178 struct GNUNET_CONTAINER_MultiHashMap *sensors;
179
180 /**
181  * Supported sources of sensor information
182  */
183 static const char *sources[] = { "gnunet-statistics", "process", NULL };
184
185 /**
186  * Supported datatypes of sensor information
187  */
188 static const char *datatypes[] = { "uint64", "double", "string", NULL };
189
190 /**
191  * Handle to statistics service
192  */
193 struct GNUNET_STATISTICS_Handle *statistics;
194
195 /**
196  * Remove sensor execution from scheduler
197  *
198  * @param cls unused
199  * @param key hash of sensor name, key to hashmap
200  * @param value a 'struct SensorInfo *'
201  * @return #GNUNET_YES if we should continue to
202  *         iterate,
203  *         #GNUNET_NO if not.
204  */
205 int destroy_sensor(void *cls,
206     const struct GNUNET_HashCode *key, void *value)
207 {
208   struct SensorInfo *sensorinfo = value;
209
210   if(NULL != sensorinfo->gnunet_stat_get_handle)
211   {
212     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Canceling a statistics get request for sensor `%s'\n", sensorinfo->name);
213     GNUNET_STATISTICS_get_cancel(sensorinfo->gnunet_stat_get_handle);
214   }
215   if(GNUNET_SCHEDULER_NO_TASK != sensorinfo->execution_task)
216   {
217     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Unscheduling sensor `%s'\n", sensorinfo->name);
218     GNUNET_SCHEDULER_cancel(sensorinfo->execution_task);
219     sensorinfo->execution_task = GNUNET_SCHEDULER_NO_TASK;
220   }
221   GNUNET_free(sensorinfo);
222   return GNUNET_YES;
223 }
224
225 /**
226  * Task run during shutdown.
227  *
228  * @param cls unused
229  * @param tc unused
230  */
231 static void
232 shutdown_task (void *cls,
233                const struct GNUNET_SCHEDULER_TaskContext *tc)
234 {
235   GNUNET_CONTAINER_multihashmap_iterate(sensors, &destroy_sensor, NULL);
236   GNUNET_CONTAINER_multihashmap_destroy(sensors);
237   if(NULL != statistics)
238     GNUNET_STATISTICS_destroy(statistics, GNUNET_YES);
239   GNUNET_SCHEDULER_shutdown();
240 }
241
242
243 /**
244  * A client disconnected.  Remove all of its data structure entries.
245  *
246  * @param cls closure, NULL
247  * @param client identification of the client
248  */
249 static void
250 handle_client_disconnect (void *cls,
251                           struct GNUNET_SERVER_Client
252                           * client)
253 {
254 }
255
256 /**
257  * Parses a version number string into major and minor
258  *
259  * @param version full version string
260  * @param major pointer to parsed major value
261  * @param minor pointer to parsed minor value
262  * @return #GNUNET_OK if parsing went ok, #GNUNET_SYSERROR in case of error
263  */
264 static int
265 version_parse(char *version, uint16_t *major, uint16_t *minor)
266 {
267   int majorval = 0;
268   int minorval = 0;
269
270   for(; isdigit(*version); version++)
271   {
272     majorval *= 10;
273     majorval += *version - '0';
274   }
275   if(*version != '.')
276     return GNUNET_SYSERR;
277   version++;
278   for(; isdigit(*version); version++)
279   {
280     minorval *= 10;
281     minorval += *version - '0';
282   }
283   if(*version != 0)
284     return GNUNET_SYSERR;
285   *major = majorval;
286   *minor = minorval;
287
288   return GNUNET_OK;
289 }
290
291 /**
292  * Load sensor definition from configuration
293  *
294  * @param cfg configuration handle
295  * @param sectionname configuration section containing definition
296  */
297 static struct SensorInfo *
298 load_sensor_from_cfg(struct GNUNET_CONFIGURATION_Handle *cfg, const char *sectionname)
299 {
300   struct SensorInfo *sensor;
301   char *version_str;
302   char *starttime_str;
303   char *endtime_str;
304   unsigned long long time_sec;
305
306   sensor = GNUNET_new(struct SensorInfo);
307   //name
308   sensor->name = GNUNET_strdup(sectionname);
309   //version
310   if(GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(cfg, sectionname, "VERSION", &version_str))
311   {
312     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Error reading sensor version\n"));
313     GNUNET_free(sensor);
314     return NULL;
315   }
316   if(GNUNET_OK != version_parse(version_str, &(sensor->version_major), &(sensor->version_minor)))
317   {
318     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Invalid sensor version number, format should be major.minor\n"));
319     GNUNET_free(sensor);
320     GNUNET_free(version_str);
321     return NULL;
322   }
323   GNUNET_free(version_str);
324   //description
325   GNUNET_CONFIGURATION_get_value_string(cfg, sectionname, "DESCRIPTION", &sensor->description);
326   //category
327   if(GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(cfg, sectionname, "CATEGORY", &sensor->category) ||
328         NULL == sensor->category)
329   {
330     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Error reading sensor category\n"));
331     GNUNET_free(sensor);
332     return NULL;
333   }
334   //enabled
335   if(GNUNET_NO == GNUNET_CONFIGURATION_get_value_yesno(cfg, sectionname, "ENABLED"))
336     sensor->enabled = GNUNET_NO;
337   else
338     sensor->enabled = GNUNET_YES;
339   //start time
340   sensor->start_time = NULL;
341   if(GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, sectionname, "START_TIME", &starttime_str))
342   {
343     GNUNET_STRINGS_fancy_time_to_absolute(starttime_str, sensor->start_time);
344     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Start time loaded: `%s'. Parsed: %d\n", starttime_str, (NULL != sensor->start_time));
345     GNUNET_free(starttime_str);
346   }
347   //end time
348   sensor->end_time = NULL;
349   if(GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, sectionname, "END_TIME", &endtime_str))
350   {
351     GNUNET_STRINGS_fancy_time_to_absolute(endtime_str, sensor->end_time);
352     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "End time loaded: `%s'. Parsed: %d\n", endtime_str, (NULL != sensor->end_time));
353     GNUNET_free(endtime_str);
354   }
355   //interval
356   if(GNUNET_OK != GNUNET_CONFIGURATION_get_value_number(cfg, sectionname, "INTERVAL", &time_sec))
357   {
358     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Error reading sensor run interval\n"));
359     GNUNET_free(sensor);
360     return NULL;
361   }
362   if(time_sec < MIN_INTERVAL)
363   {
364     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Sensor run interval too low (%" PRIu64 " < %d)\n"),
365         time_sec, MIN_INTERVAL);
366     GNUNET_free(sensor);
367     return NULL;
368   }
369   sensor->interval = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, time_sec);
370   //lifetime
371   if(GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, sectionname, "LIFETIME", &time_sec))
372   {
373     sensor->lifetime = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, time_sec);
374   }
375   else
376     sensor->lifetime = GNUNET_TIME_UNIT_FOREVER_REL;
377   //capabilities TODO
378   //source
379   if(GNUNET_OK != GNUNET_CONFIGURATION_get_value_choice(cfg, sectionname, "SOURCE", sources, (const char **)&sensor->source))
380   {
381     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Error reading sensor source\n"));
382     GNUNET_free(sensor);
383     return NULL;
384   }
385   if(sources[0] == sensor->source) //gnunet-statistics
386   {
387     if(GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(cfg, sectionname, "GNUNET_STAT_SERVICE", &sensor->gnunet_stat_service) ||
388         GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(cfg, sectionname, "GNUNET_STAT_NAME", &sensor->gnunet_stat_name))
389     {
390       GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Error reading sensor gnunet-statistics source information\n"));
391       GNUNET_free(sensor);
392       return NULL;
393     }
394     sensor->gnunet_stat_get_handle = NULL;
395   }
396   else if(sources[1] == sensor->source) //process
397   {
398     if(GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(cfg, sectionname, "EXT_PROCESS", &sensor->ext_process))
399     {
400       GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Error reading sensor process name\n"));
401       GNUNET_free(sensor);
402       return NULL;
403     }
404     GNUNET_CONFIGURATION_get_value_string(cfg, sectionname, "EXT_ARGS", &sensor->ext_args);
405   }
406   //expected datatype
407   if(GNUNET_OK != GNUNET_CONFIGURATION_get_value_choice(cfg, sectionname, "EXPECTED_DATATYPE", datatypes, (const char **)&sensor->expected_datatype))
408   {
409     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Error reading sensor expected datatype\n"));
410     GNUNET_free(sensor);
411     return NULL;
412   }
413   if(sources[0] == sensor->source && datatypes[0] != sensor->expected_datatype)
414   {
415     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Invalid expected datatype, gnunet-statistics returns uint64 values\n"));
416     GNUNET_free(sensor);
417     return NULL;
418   }
419   //TODO: reporting mechanism
420   //execution task
421   sensor->execution_task = GNUNET_SCHEDULER_NO_TASK;
422   //running
423   sensor->running = GNUNET_NO;
424
425   return sensor;
426 }
427
428 /**
429  * Load sensor definition from file
430  *
431  * @param filename full path to file containing sensor definition
432  */
433 static struct SensorInfo *
434 load_sensor_from_file(const char *filename)
435 {
436   struct GNUNET_CONFIGURATION_Handle *sensorcfg;
437   const char *filebasename;
438   struct SensorInfo *sensor;
439
440   //test file
441   if(GNUNET_YES != GNUNET_DISK_file_test(filename))
442   {
443     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Failed to access sensor file: %s\n"), filename);
444     return NULL;
445   }
446   //load file as configuration
447   sensorcfg = GNUNET_CONFIGURATION_create();
448   if(GNUNET_SYSERR == GNUNET_CONFIGURATION_parse(sensorcfg, filename))
449   {
450     GNUNET_CONFIGURATION_destroy(sensorcfg);
451     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Failed to load sensor definition: %s\n"), filename);
452     return NULL;
453   }
454   //configuration section should be the same as filename
455   filebasename = GNUNET_STRINGS_get_short_name(filename);
456   sensor = load_sensor_from_cfg(sensorcfg, filebasename);
457   sensor->def_file = GNUNET_strdup(filename);
458
459   GNUNET_CONFIGURATION_destroy(sensorcfg);
460
461   return sensor;
462 }
463
464 /**
465  * Compares version numbers of two sensors
466  *
467  * @param s1 first sensor
468  * @param s2 second sensor
469  * @return 1: s1 > s2, 0: s1 == s2, -1: s1 < s2
470  */
471 static int
472 sensor_version_compare(struct SensorInfo *s1, struct SensorInfo *s2)
473 {
474   if(s1->version_major == s2->version_major)
475     return (s1->version_minor < s2->version_minor) ? -1 : (s1->version_minor > s2->version_minor);
476   else
477     return (s1->version_major < s2->version_major) ? -1 : (s1->version_major > s2->version_major);
478 }
479
480 /**
481  * Adds a new sensor to given hashmap.
482  * If the same name exist, compares versions and update if old.
483  *
484  * @param sensor Sensor structure to add
485  * @param map Hashmap to add to
486  * @return #GNUNET_YES if added, #GNUNET_NO if not added which is not necessarily an error
487  */
488 static int
489 add_sensor_to_hashmap(struct SensorInfo *sensor, struct GNUNET_CONTAINER_MultiHashMap *map)
490 {
491   struct GNUNET_HashCode key;
492   struct SensorInfo *existing;
493
494   GNUNET_CRYPTO_hash(sensor->name, strlen(sensor->name), &key);
495   existing = GNUNET_CONTAINER_multihashmap_get(map, &key);
496   if(NULL != existing) //sensor with same name already exists
497   {
498     if(sensor_version_compare(existing, sensor) >= 0) //same or newer version already exist
499     {
500       GNUNET_log(GNUNET_ERROR_TYPE_INFO, _("Sensor `%s' already exists with same or newer version\n"), sensor->name);
501       return GNUNET_NO;
502     }
503     else
504     {
505       GNUNET_CONTAINER_multihashmap_remove(map, &key, existing); //remove the old version
506       GNUNET_free(existing);
507       GNUNET_log(GNUNET_ERROR_TYPE_INFO, _("Upgrading sensor `%s' to a newer version\n"), sensor->name);
508     }
509   }
510   if(GNUNET_SYSERR == GNUNET_CONTAINER_multihashmap_put(map, &key, sensor, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
511   {
512     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Error adding new sensor `%s' to global hashmap, this should not happen\n"), sensor->name);
513     return GNUNET_NO;
514   }
515
516   return GNUNET_YES;
517 }
518
519 /**
520  * Iterating over files in sensors directory
521  *
522  * @param cls closure
523  * @param filename complete filename (absolute path)
524  * @return #GNUNET_OK to continue to iterate
525  */
526 static int
527 reload_sensors_dir_cb(void *cls, const char *filename)
528 {
529   struct SensorInfo *sensor;
530
531   if(GNUNET_YES != GNUNET_DISK_file_test(filename))
532     return GNUNET_OK;
533   sensor = load_sensor_from_file(filename);
534   if(NULL == sensor)
535   {
536     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("Error loading sensor from file: %s\n"), filename);
537     return GNUNET_OK;
538   }
539   if(GNUNET_YES == add_sensor_to_hashmap(sensor, sensors))
540     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, _("Sensor `%s' added to global hashmap\n"), sensor->name);
541   else
542     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, ("Could not add sensor `%s' to global hashmap\n"), sensor->name);
543
544   return GNUNET_OK;
545 }
546
547 /*
548  * Get path to the directory containing the sensor definition files
549  *
550  * @return sensor files directory
551  */
552 static char *
553 get_sensor_dir()
554 {
555   char* datadir;
556   char* sensordir;
557
558   datadir = GNUNET_OS_installation_get_path(GNUNET_OS_IPK_DATADIR);
559   GNUNET_asprintf(&sensordir, "%ssensors%s",
560       datadir, DIR_SEPARATOR_STR);
561
562   return sensordir;
563 }
564
565 /**
566  * Reads sensor definitions from data files
567  *
568  */
569 static void
570 reload_sensors()
571 {
572   char* sensordir;
573
574   sensordir = get_sensor_dir();
575   GNUNET_log(GNUNET_ERROR_TYPE_INFO, _("Reloading sensor definitions from directory `%s'\n"), sensordir);
576   GNUNET_assert(GNUNET_YES == GNUNET_DISK_directory_test(sensordir, GNUNET_YES));
577
578   //read all files in sensors directory
579   GNUNET_DISK_directory_scan(sensordir, &reload_sensors_dir_cb, NULL);
580   GNUNET_log(GNUNET_ERROR_TYPE_INFO, _("Loaded %d sensors from directory `%s'\n"),
581       GNUNET_CONTAINER_multihashmap_size(sensors), sensordir);
582 }
583
584 /**
585  * Creates a structure with basic sensor info to be sent to a client
586  *
587  * @param sensor sensor information
588  * @return message ready to be sent to client
589  */
590 static struct SensorInfoMessage *
591 create_sensor_info_msg(struct SensorInfo *sensor)
592 {
593   struct SensorInfoMessage *msg;
594   uint16_t len;
595   size_t name_len;
596   size_t desc_len;
597   char *str_ptr;
598
599   name_len = strlen(sensor->name);
600   if(NULL == sensor->description)
601     desc_len = 0;
602   else
603     desc_len = strlen(sensor->description) + 1;
604   len = 0;
605   len += sizeof(struct SensorInfoMessage);
606   len += name_len;
607   len += desc_len;
608   msg = GNUNET_malloc(len);
609   msg->header.size = htons(len);
610   msg->header.type = htons(GNUNET_MESSAGE_TYPE_SENSOR_INFO);
611   msg->name_len = htons(name_len);
612   msg->description_len = htons(desc_len);
613   msg->version_major = htons(sensor->version_major);
614   msg->version_minor = htons(sensor->version_minor);
615   str_ptr = (char*) &msg[1];
616   memcpy(str_ptr, sensor->name, name_len);
617   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending sensor name (%d): %.*s\n",
618         name_len, name_len, str_ptr);
619   str_ptr += name_len;
620   memcpy(str_ptr, sensor->description, desc_len);
621   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending sensor description (%d): %.*s\n",
622           desc_len, desc_len, str_ptr);
623
624   return msg;
625 }
626
627 /**
628  * Handle GET SENSOR message.
629  *
630  * @param cls closure
631  * @param client identification of the client
632  * @param message the actual message
633  */
634 static void
635 handle_get_sensor (void *cls, struct GNUNET_SERVER_Client *client,
636             const struct GNUNET_MessageHeader *message)
637 {
638   struct GNUNET_SERVER_TransmitContext *tc;
639   char *sensorname;
640   size_t sensorname_len;
641   struct GNUNET_HashCode key;
642   struct SensorInfo *sensorinfo;
643   struct SensorInfoMessage *msg;
644
645   sensorname = (char *)&message[1];
646   sensorname_len = ntohs(message->size) - sizeof(struct GNUNET_MessageHeader);
647   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "`%s' message received for sensor (%d) `%.*s'\n",
648               "GET SENSOR", sensorname_len, sensorname_len, sensorname);
649   tc = GNUNET_SERVER_transmit_context_create (client);
650   GNUNET_CRYPTO_hash(sensorname, sensorname_len, &key);
651   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Created key hash for requested sensor\n");
652   sensorinfo = (struct SensorInfo *)GNUNET_CONTAINER_multihashmap_get(sensors, &key);
653   if(NULL != sensorinfo)
654   {
655     msg = create_sensor_info_msg(sensorinfo);
656     GNUNET_SERVER_transmit_context_append_message(tc, (struct GNUNET_MessageHeader *)msg);
657     GNUNET_free(msg);
658   }
659   else
660     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Requested sensor `%.*s' was not found\n",
661         sensorname_len, sensorname);
662   GNUNET_SERVER_transmit_context_append_data(tc, NULL, 0, GNUNET_MESSAGE_TYPE_SENSOR_END);
663   GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
664 }
665
666 /**
667  * Iterator for sensors and adds them to transmit context
668  *
669  * @param cls a 'struct GNUNET_SERVER_TransmitContext *'
670  * @param key hash of sensor name, key to hashmap
671  * @param value a 'struct SensorInfo *'
672  */
673 int add_sensor_to_tc(void *cls,
674     const struct GNUNET_HashCode *key, void *value)
675 {
676   struct GNUNET_SERVER_TransmitContext *tc = cls;
677   struct SensorInfo *sensorinfo = value;
678   struct SensorInfoMessage *msg;
679
680   msg = create_sensor_info_msg(sensorinfo);
681   GNUNET_SERVER_transmit_context_append_message(tc, (struct GNUNET_MessageHeader *)msg);
682
683   GNUNET_free(msg);
684
685   return GNUNET_YES;
686 }
687
688 /**
689  * Handle GET ALL SENSORS message.
690  *
691  * @param cls closure
692  * @param client identification of the client
693  * @param message the actual message
694  */
695 static void
696 handle_get_all_sensors (void *cls, struct GNUNET_SERVER_Client *client,
697             const struct GNUNET_MessageHeader *message)
698 {
699   struct GNUNET_SERVER_TransmitContext *tc;
700
701   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "`%s' message received.\n",
702                 "GET ALL SENSOR");
703   tc = GNUNET_SERVER_transmit_context_create (client);
704   GNUNET_CONTAINER_multihashmap_iterate(sensors, &add_sensor_to_tc, tc);
705   GNUNET_SERVER_transmit_context_append_data(tc, NULL, 0, GNUNET_MESSAGE_TYPE_SENSOR_END);
706   GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
707 }
708
709 /**
710  * Do a series of checks to determine if sensor should execute
711  *
712  * @return #GNUNET_YES / #GNUNET_NO
713  */
714 static int
715 should_run_sensor(struct SensorInfo *sensorinfo)
716 {
717   //FIXME: some checks should disable the sensor (e.g. expired)
718   struct GNUNET_TIME_Absolute now;
719
720   if(GNUNET_NO == sensorinfo->enabled)
721   {
722     GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Sensor `%s' is disabled, will not run\n", sensorinfo->name);
723     return GNUNET_NO;
724   }
725   now = GNUNET_TIME_absolute_get();
726   if(NULL != sensorinfo->start_time
727       && now.abs_value_us < sensorinfo->start_time->abs_value_us)
728   {
729     GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Start time for sensor `%s' not reached yet, will not run\n", sensorinfo->name);
730     return GNUNET_NO;
731   }
732   if(NULL != sensorinfo->end_time
733       && now.abs_value_us >= sensorinfo->end_time->abs_value_us)
734   {
735     GNUNET_log(GNUNET_ERROR_TYPE_INFO, "End time for sensor `%s' passed, will not run\n", sensorinfo->name);
736     return GNUNET_NO;
737   }
738   return GNUNET_YES;
739 }
740
741 /**
742  * Callback function to process statistic values
743  *
744  * @param cls 'struct SensorInfo *'
745  * @param subsystem name of subsystem that created the statistic
746  * @param name the name of the datum
747  * @param value the current value
748  * @param is_persistent #GNUNET_YES if the value is persistent, #GNUNET_NO if not
749  * @return #GNUNET_OK to continue, #GNUNET_SYSERR to abort iteration
750  */
751 int sensor_statistics_iterator (void *cls,
752     const char *subsystem,
753     const char *name,
754     uint64_t value,
755     int is_persistent)
756 {
757   struct SensorInfo *sensorinfo = cls;
758
759   GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Received a value for sensor `%s': %" PRIu64 "\n", sensorinfo->name, value);
760   return GNUNET_OK;
761 }
762
763 /**
764  * Continuation called after sensor gets all gnunet statistics values
765  *
766  * @param cls 'struct SensorInfo *'
767  * @param success #GNUNET_OK if statistics were
768  *        successfully obtained, #GNUNET_SYSERR if not.
769  */
770 void end_sensor_run_stat (void *cls, int success)
771 {
772   struct SensorInfo *sensorinfo = cls;
773
774   sensorinfo->gnunet_stat_get_handle = NULL;
775   sensorinfo->running = GNUNET_NO;
776 }
777
778 /**
779  * Callback for output of executed sensor process
780  *
781  * @param cls 'struct SensorInfo *'
782  * @param line line of output from a command, NULL for the end
783  */
784 void sensor_process_callback (void *cls, const char *line)
785 {
786   struct SensorInfo *sensorinfo = cls;
787
788   if(NULL == line)
789   {
790     sensorinfo->running = GNUNET_NO;
791     return;
792   }
793   GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Received a value for sensor `%s': %s\n", sensorinfo->name, line);
794 }
795
796 /**
797  * Actual execution of a sensor
798  *
799  * @param cls 'struct SensorInfo'
800  * @param tc unsed
801  */
802 void
803 sensor_run (void *cls,
804     const struct GNUNET_SCHEDULER_TaskContext * tc)
805 {
806   struct SensorInfo *sensorinfo = cls;
807   int check_result;
808   char *sensors_dir;
809   char *process_path;
810
811   sensorinfo->execution_task = GNUNET_SCHEDULER_add_delayed(sensorinfo->interval, &sensor_run, sensorinfo);
812   if(GNUNET_YES == sensorinfo->running) //FIXME: should we try to kill?
813   {
814     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Sensor `%s' running for too long, will try again next interval\n", sensorinfo->name);
815     return;
816   }
817   if(GNUNET_NO == should_run_sensor(sensorinfo))
818     return;
819   sensorinfo->running = GNUNET_YES;
820   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Starting the execution of sensor `%s'\n", sensorinfo->name);
821   if(sources[0] == sensorinfo->source) //gnunet-statistics
822   {
823     if(NULL == statistics)
824     {
825       statistics = GNUNET_STATISTICS_create("sensor", cfg);
826     }
827     sensorinfo->gnunet_stat_get_handle = GNUNET_STATISTICS_get(statistics,
828         sensorinfo->gnunet_stat_service,
829         sensorinfo->gnunet_stat_name,
830         sensorinfo->interval, //try to get values only for the interval of the sensor
831         &end_sensor_run_stat,
832         &sensor_statistics_iterator,
833         sensorinfo);
834   }
835   else if(sources[1] == sensorinfo->source)
836   {
837     //FIXME: break execution if process is a path
838     //check if the process exists in $PATH
839     process_path = GNUNET_strdup(sensorinfo->ext_process);
840     check_result =
841         GNUNET_OS_check_helper_binary(sensorinfo->ext_process, GNUNET_NO, NULL); //search in $PATH
842     if(GNUNET_SYSERR == check_result)
843     {
844       //search in sensor directory
845       sensors_dir = get_sensor_dir();
846       GNUNET_free(process_path);
847       GNUNET_asprintf(&process_path, "%s%s-files%s%s",
848           sensors_dir,
849           sensorinfo->name,
850           DIR_SEPARATOR_STR,
851           sensorinfo->ext_process);
852       GNUNET_free(sensors_dir);
853       check_result =
854         GNUNET_OS_check_helper_binary(process_path, GNUNET_NO, NULL);
855     }
856     if(GNUNET_SYSERR == check_result)
857     {
858       GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Sensor `%s' process `%s' problem: binary doesn't exist or not executable\n",
859           sensorinfo->name,
860           sensorinfo->ext_process);
861       //FIXME: disable sensor here?
862       sensorinfo->running = GNUNET_NO;
863       GNUNET_free(process_path);
864       return;
865     }
866     GNUNET_OS_command_run(&sensor_process_callback,
867         sensorinfo,
868         GNUNET_TIME_UNIT_FOREVER_REL,
869         process_path,
870         sensorinfo->ext_process,
871         sensorinfo->ext_args,
872         NULL);
873     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Process started for sensor `%s'\n", sensorinfo->name);
874   }
875   else
876   {
877     sensorinfo->running = GNUNET_NO;
878     GNUNET_break(0); //shouldn't happen
879   }
880 }
881
882 /**
883  * Starts the execution of a sensor
884  *
885  * @param cls unused
886  * @param key hash of sensor name, key to hashmap (unused)
887  * @param value a 'struct SensorInfo *'
888  * @return #GNUNET_YES if we should continue to
889  *         iterate,
890  *         #GNUNET_NO if not.
891  */
892 int schedule_sensor(void *cls,
893     const struct GNUNET_HashCode *key, void *value)
894 {
895   struct SensorInfo *sensorinfo = value;
896
897   if(GNUNET_NO == should_run_sensor(sensorinfo))
898     return GNUNET_YES;
899   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Scheduling sensor `%s' to run after %" PRIu64 " microseconds\n",
900       sensorinfo->name, sensorinfo->interval.rel_value_us);
901   if(GNUNET_SCHEDULER_NO_TASK != sensorinfo->execution_task)
902   {
903     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Sensor `%s' execution task already set, this should not happen\n", sensorinfo->name);
904     return GNUNET_NO;
905   }
906   sensorinfo->execution_task = GNUNET_SCHEDULER_add_delayed(sensorinfo->interval, &sensor_run, sensorinfo);
907   return GNUNET_YES;
908 }
909
910 /**
911  * Starts the execution of all enabled sensors
912  *
913  */
914 static void
915 schedule_all_sensors()
916 {
917   GNUNET_CONTAINER_multihashmap_iterate(sensors, &schedule_sensor, NULL);
918 }
919
920 /**
921  * Process statistics requests.
922  *
923  * @param cls closure
924  * @param server the initialized server
925  * @param c configuration to use
926  */
927 static void
928 run (void *cls,
929      struct GNUNET_SERVER_Handle *server,
930      const struct GNUNET_CONFIGURATION_Handle *c)
931 {
932   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
933     {&handle_get_sensor, NULL, GNUNET_MESSAGE_TYPE_SENSOR_GET,
934      0},
935     {&handle_get_all_sensors, NULL, GNUNET_MESSAGE_TYPE_SENSOR_GETALL,
936      sizeof (struct GNUNET_MessageHeader)},
937     {NULL, NULL, 0, 0}
938   };
939
940   cfg = c;
941   sensors = GNUNET_CONTAINER_multihashmap_create(10, GNUNET_NO);
942   reload_sensors();
943   schedule_all_sensors();
944   GNUNET_SERVER_add_handlers (server, handlers);
945   GNUNET_SERVER_disconnect_notify (server, 
946                                    &handle_client_disconnect,
947                                    NULL);
948   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
949                                 &shutdown_task,
950                                 NULL);
951 }
952
953
954 /**
955  * The main function for the sensor service.
956  *
957  * @param argc number of arguments from the command line
958  * @param argv command line arguments
959  * @return 0 ok, 1 on error
960  */
961 int
962 main (int argc, char *const *argv)
963 {
964   return (GNUNET_OK ==
965           GNUNET_SERVICE_run (argc,
966                               argv,
967                               "sensor",
968                               GNUNET_SERVICE_OPTION_NONE,
969                               &run, NULL)) ? 0 : 1;
970 }
971
972 /* end of gnunet-service-sensor.c */