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