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