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