sensor: towards update functionality
[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  * Our configuration.
35  */
36 static const struct GNUNET_CONFIGURATION_Handle *cfg;
37
38 /**
39  * Hashmap of loaded sensor definitions
40  */
41 static struct GNUNET_CONTAINER_MultiHashMap *sensors;
42
43 /**
44  * Handle to statistics service
45  */
46 struct GNUNET_STATISTICS_Handle *statistics;
47
48 /**
49  * Handle to peerstore service
50  */
51 struct GNUNET_PEERSTORE_Handle *peerstore;
52
53 /**
54  * Service name
55  */
56 char *subsystem = "sensor";
57
58 /**
59  * My peer id
60  */
61 struct GNUNET_PeerIdentity peerid;
62
63 /**
64  * Change the state of the sensor.
65  * Write the change to file to make it persistent.
66  *
67  * @param sensor sensor info struct
68  * @param state new enabled state: #GNUNET_YES / #GNUNET_NO
69  */
70 static void
71 set_sensor_enabled (struct GNUNET_SENSOR_SensorInfo *sensor, int state)
72 {
73   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
74              "Sensor `%s': Setting enabled to %d.\n",
75              sensor->name, state);
76   sensor->enabled = GNUNET_NO;
77   GNUNET_assert (NULL != sensor->cfg);
78   GNUNET_CONFIGURATION_set_value_string (sensor->cfg,
79                                          sensor->name,
80                                          "ENABLED",
81                                          (GNUNET_YES == state) ? "YES" : "NO");
82   GNUNET_CONFIGURATION_write (sensor->cfg, sensor->def_file);
83 }
84
85 /**
86  * Task run during shutdown.
87  *
88  * @param cls unused
89  * @param tc unused
90  */
91 static void
92 shutdown_task (void *cls,
93                const struct GNUNET_SCHEDULER_TaskContext *tc)
94 {
95   SENSOR_update_stop ();
96   SENSOR_reporting_stop ();
97   SENSOR_analysis_stop ();
98   GNUNET_SENSOR_destroy_sensors (sensors);
99   if (NULL != statistics)
100   {
101     GNUNET_STATISTICS_destroy (statistics, GNUNET_YES);
102     statistics = NULL;
103   }
104   if (NULL != peerstore)
105   {
106     GNUNET_PEERSTORE_disconnect (peerstore, GNUNET_YES);
107     peerstore = NULL;
108   }
109   GNUNET_SCHEDULER_shutdown ();
110 }
111
112
113 /**
114  * A client disconnected.  Remove all of its data structure entries.
115  *
116  * @param cls closure, NULL
117  * @param client identification of the client
118  */
119 static void
120 handle_client_disconnect (void *cls,
121                           struct GNUNET_SERVER_Client *client)
122 {
123 }
124
125 /**
126  * Creates a structure with basic sensor info to be sent to a client.
127  *
128  * @param sensor sensor information
129  * @return message ready to be sent to client
130  */
131 static struct SensorInfoMessage *
132 create_sensor_info_msg (struct GNUNET_SENSOR_SensorInfo *sensor)
133 {
134   struct SensorInfoMessage *msg;
135   uint16_t len;
136   size_t name_len;
137   size_t desc_len;
138   char *str_ptr;
139
140   name_len = strlen(sensor->name);
141   if(NULL == sensor->description)
142     desc_len = 0;
143   else
144     desc_len = strlen(sensor->description) + 1;
145   len = 0;
146   len += sizeof(struct SensorInfoMessage);
147   len += name_len;
148   len += desc_len;
149   msg = GNUNET_malloc(len);
150   msg->header.size = htons(len);
151   msg->header.type = htons(GNUNET_MESSAGE_TYPE_SENSOR_INFO);
152   msg->name_len = htons(name_len);
153   msg->description_len = htons(desc_len);
154   msg->version_major = htons(sensor->version_major);
155   msg->version_minor = htons(sensor->version_minor);
156   str_ptr = (char*) &msg[1];
157   memcpy(str_ptr, sensor->name, name_len);
158   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending sensor name (%d): %.*s\n",
159         name_len, name_len, str_ptr);
160   str_ptr += name_len;
161   memcpy(str_ptr, sensor->description, desc_len);
162   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending sensor description (%d): %.*s\n",
163           desc_len, desc_len, str_ptr);
164
165   return msg;
166 }
167
168 /**
169  * Handle GET SENSOR message.
170  *
171  * @param cls closure
172  * @param client identification of the client
173  * @param message the actual message
174  */
175 static void
176 handle_get_sensor (void *cls,
177                    struct GNUNET_SERVER_Client *client,
178                    const struct GNUNET_MessageHeader *message)
179 {
180   struct GNUNET_SERVER_TransmitContext *tc;
181   char *sensorname;
182   size_t sensorname_len;
183   struct GNUNET_HashCode key;
184   struct GNUNET_SENSOR_SensorInfo *sensorinfo;
185   struct SensorInfoMessage *msg;
186
187   sensorname = (char *)&message[1];
188   sensorname_len = ntohs(message->size) - sizeof(struct GNUNET_MessageHeader);
189   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "`%s' message received for sensor (%d) `%.*s'\n",
190               "GET SENSOR", sensorname_len, sensorname_len, sensorname);
191   tc = GNUNET_SERVER_transmit_context_create (client);
192   GNUNET_CRYPTO_hash(sensorname, sensorname_len, &key);
193   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Created key hash for requested sensor\n");
194   sensorinfo = (struct GNUNET_SENSOR_SensorInfo *)GNUNET_CONTAINER_multihashmap_get(sensors, &key);
195   if(NULL != sensorinfo)
196   {
197     msg = create_sensor_info_msg(sensorinfo);
198     GNUNET_SERVER_transmit_context_append_message(tc, (struct GNUNET_MessageHeader *)msg);
199     GNUNET_free(msg);
200   }
201   else
202     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Requested sensor `%.*s' was not found\n",
203         sensorname_len, sensorname);
204   GNUNET_SERVER_transmit_context_append_data(tc, NULL, 0, GNUNET_MESSAGE_TYPE_SENSOR_END);
205   GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
206 }
207
208 /**
209  * Iterator for sensors and adds them to transmit context
210  *
211  * @param cls a `struct GNUNET_SERVER_TransmitContext *`
212  * @param key hash of sensor name, key to hashmap
213  * @param value a `struct GNUNET_SENSOR_SensorInfo *`
214  */
215 static int
216 add_sensor_to_tc (void *cls,
217                   const struct GNUNET_HashCode *key,
218                   void *value)
219 {
220   struct GNUNET_SERVER_TransmitContext *tc = cls;
221   struct GNUNET_SENSOR_SensorInfo *sensorinfo = value;
222   struct SensorInfoMessage *msg;
223
224   msg = create_sensor_info_msg(sensorinfo);
225   GNUNET_SERVER_transmit_context_append_message(tc, (struct GNUNET_MessageHeader *)msg);
226
227   GNUNET_free(msg);
228
229   return GNUNET_YES;
230 }
231
232 /**
233  * Handle GET ALL SENSORS message.
234  *
235  * @param cls closure
236  * @param client identification of the client
237  * @param message the actual message
238  */
239 static void
240 handle_get_all_sensors (void *cls, struct GNUNET_SERVER_Client *client,
241             const struct GNUNET_MessageHeader *message)
242 {
243   struct GNUNET_SERVER_TransmitContext *tc;
244
245   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "`%s' message received.\n",
246                 "GET ALL SENSOR");
247   tc = GNUNET_SERVER_transmit_context_create (client);
248   GNUNET_CONTAINER_multihashmap_iterate(sensors, &add_sensor_to_tc, tc);
249   GNUNET_SERVER_transmit_context_append_data(tc, NULL, 0, GNUNET_MESSAGE_TYPE_SENSOR_END);
250   GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
251 }
252
253 /**
254  * Do a series of checks to determine if sensor should execute
255  *
256  * @return #GNUNET_YES / #GNUNET_NO
257  */
258 static int
259 should_run_sensor(struct GNUNET_SENSOR_SensorInfo *sensorinfo)
260 {
261   struct GNUNET_TIME_Absolute now;
262
263   if(GNUNET_NO == sensorinfo->enabled)
264   {
265     GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Sensor `%s' is disabled, will not run\n", sensorinfo->name);
266     return GNUNET_NO;
267   }
268   now = GNUNET_TIME_absolute_get();
269   if(NULL != sensorinfo->start_time
270       && now.abs_value_us < sensorinfo->start_time->abs_value_us)
271   {
272     GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Start time for sensor `%s' not reached yet, will not run\n", sensorinfo->name);
273     return GNUNET_NO;
274   }
275   if(NULL != sensorinfo->end_time
276       && now.abs_value_us >= sensorinfo->end_time->abs_value_us)
277   {
278     GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Sensor `%s' expired, disabling.\n", sensorinfo->name);
279     set_sensor_enabled(sensorinfo, GNUNET_NO);
280     return GNUNET_NO;
281   }
282   return GNUNET_YES;
283 }
284
285 /**
286  * Callback function to process statistic values
287  *
288  * @param cls `struct GNUNET_SENSOR_SensorInfo *`
289  * @param subsystem name of subsystem that created the statistic
290  * @param name the name of the datum
291  * @param value the current value
292  * @param is_persistent #GNUNET_YES if the value is persistent, #GNUNET_NO if not
293  * @return #GNUNET_OK to continue, #GNUNET_SYSERR to abort iteration
294  */
295 static int
296 sensor_statistics_iterator (void *cls,
297                             const char *ss,
298                             const char *name,
299                             uint64_t value,
300                             int is_persistent)
301 {
302   struct GNUNET_SENSOR_SensorInfo *sensorinfo = cls;
303   double dvalue = (double)value;
304   struct GNUNET_TIME_Absolute expiry;
305
306   GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Received a value for sensor `%s': %" PRIu64 "\n", sensorinfo->name, value);
307   expiry = GNUNET_TIME_relative_to_absolute(sensorinfo->lifetime);
308   GNUNET_PEERSTORE_store(peerstore,
309       subsystem,
310       &peerid,
311       sensorinfo->name,
312       &dvalue,
313       sizeof(dvalue),
314       expiry,
315       GNUNET_PEERSTORE_STOREOPTION_MULTIPLE,
316       NULL,
317       NULL);
318   return GNUNET_SYSERR; /* We only want one value */
319 }
320
321 /**
322  * Continuation called after sensor gets all gnunet statistics values
323  *
324  * @param cls `struct GNUNET_SENSOR_SensorInfo *`
325  * @param success #GNUNET_OK if statistics were
326  *        successfully obtained, #GNUNET_SYSERR if not.
327  */
328 static void
329 end_sensor_run_stat (void *cls, int success)
330 {
331   struct GNUNET_SENSOR_SensorInfo *sensorinfo = cls;
332
333   sensorinfo->gnunet_stat_get_handle = NULL;
334   sensorinfo->running = GNUNET_NO;
335 }
336
337 /**
338  * Tries to parse a received sensor value to its
339  * expected datatype
340  *
341  * @param value the string value received, should be null terminated
342  * @param sensor sensor information struct
343  * @param ret pointer to parsed value
344  * @return size of new parsed value, 0 for error
345  */
346 static size_t
347 parse_sensor_value (const char *value,
348                     struct GNUNET_SENSOR_SensorInfo *sensor,
349                     void **ret)
350 {
351   double *dval;
352   char *endptr;
353
354   *ret = NULL;
355   if ('\0' == *value)
356     return 0;
357   if(0 == strcmp("numeric", sensor->expected_datatype))
358   {
359     dval = GNUNET_new(double);
360     *dval = strtod(value, &endptr);
361     if(value == endptr)
362       return 0;
363    *ret = dval;
364    return sizeof(double);
365   }
366   if(0 == strcmp("string", sensor->expected_datatype))
367   {
368     *ret = GNUNET_strdup(value);
369     return strlen(value) + 1;
370   }
371   GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
372       _("Unknown value type expected by sensor, this should not happen.\n"));
373   return 0;
374 }
375
376 /**
377  * Callback for output of executed sensor process
378  *
379  * @param cls `struct GNUNET_SENSOR_SensorInfo *`
380  * @param line line of output from a command, NULL for the end
381  */
382 static void
383 sensor_process_callback (void *cls, const char *line)
384 {
385   struct GNUNET_SENSOR_SensorInfo *sensorinfo = cls;
386   void *value;
387   size_t valsize;
388   struct GNUNET_TIME_Absolute expiry;
389
390   if(NULL == line)
391   {
392     GNUNET_OS_command_stop(sensorinfo->ext_cmd);
393     sensorinfo->ext_cmd = NULL;
394     sensorinfo->running = GNUNET_NO;
395     sensorinfo->ext_cmd_value_received = GNUNET_NO;
396     return;
397   }
398   if(GNUNET_YES == sensorinfo->ext_cmd_value_received)
399     return; /* We only want one *valid* value */
400   GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Received a value for sensor `%s': %s\n", sensorinfo->name, line);
401   valsize = parse_sensor_value(line, sensorinfo, &value);
402   if (valsize == 0) /* invalid value, FIXME: should we disable the sensor now? */
403   {
404     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
405         _("Received an invalid value for sensor `%s': %s\n"),
406         sensorinfo->name, line);
407   }
408   else
409   {
410     sensorinfo->ext_cmd_value_received = GNUNET_YES;
411     expiry = GNUNET_TIME_relative_to_absolute(sensorinfo->lifetime);
412     GNUNET_PEERSTORE_store(peerstore,
413         subsystem,
414         &peerid,
415         sensorinfo->name,
416         value,
417         valsize,
418         expiry,
419         GNUNET_PEERSTORE_STOREOPTION_MULTIPLE,
420         NULL,
421         NULL);
422     GNUNET_free (value);
423   }
424 }
425
426 /**
427  * Checks if the given file is a path
428  *
429  * @return #GNUNET_YES / #GNUNET_NO
430  */
431 static int
432 is_path(char *filename)
433 {
434   size_t filename_len;
435   int i;
436
437   filename_len = strlen(filename);
438   for(i = 0; i < filename_len; i++)
439   {
440     if(DIR_SEPARATOR == filename[i])
441       return GNUNET_YES;
442   }
443   return GNUNET_NO;
444 }
445
446 /**
447  * Actual execution of a sensor
448  *
449  * @param cls 'struct SensorInfo'
450  * @param tc unsed
451  */
452 static void
453 sensor_run (void *cls,
454             const struct GNUNET_SCHEDULER_TaskContext * tc)
455 {
456   struct GNUNET_SENSOR_SensorInfo *sensorinfo = cls;
457   int check_result;
458   char *sensors_dir;
459   char *process_path;
460
461   sensorinfo->execution_task = GNUNET_SCHEDULER_add_delayed(sensorinfo->interval, &sensor_run, sensorinfo);
462   if(GNUNET_YES == sensorinfo->running) //FIXME: should we try to kill?
463   {
464     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Sensor `%s' running for too long, will try again next interval\n", sensorinfo->name);
465     return;
466   }
467   if(GNUNET_NO == should_run_sensor(sensorinfo))
468     return;
469   sensorinfo->running = GNUNET_YES;
470   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Starting the execution of sensor `%s'\n", sensorinfo->name);
471   if(0 == strcmp ("gnunet-statistics", sensorinfo->source))
472   {
473     sensorinfo->gnunet_stat_get_handle = GNUNET_STATISTICS_get(statistics,
474         sensorinfo->gnunet_stat_service,
475         sensorinfo->gnunet_stat_name,
476         sensorinfo->interval, //try to get values only for the interval of the sensor
477         &end_sensor_run_stat,
478         &sensor_statistics_iterator,
479         sensorinfo);
480   }
481   else if(0 == strcmp ("process", sensorinfo->source))
482   {
483     if(GNUNET_YES == is_path(sensorinfo->ext_process))
484     {
485       GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
486           _("Sensor `%s': External process should not be a path, disabling sensor.\n"),
487           sensorinfo->name);
488       set_sensor_enabled(sensorinfo, GNUNET_NO);
489       return;
490     }
491     //check if the process exists in $PATH
492     process_path = GNUNET_strdup(sensorinfo->ext_process);
493     check_result =
494         GNUNET_OS_check_helper_binary(process_path, GNUNET_NO, NULL);
495     if(GNUNET_SYSERR == check_result)
496     {
497       //search in sensor directory
498       sensors_dir = GNUNET_SENSOR_get_sensor_dir ();
499       GNUNET_free(process_path);
500       GNUNET_asprintf(&process_path,
501                       "%s%s-files%s%s",
502                       sensors_dir,
503                       sensorinfo->name,
504                       DIR_SEPARATOR_STR,
505                       sensorinfo->ext_process);
506       GNUNET_free(sensors_dir);
507       check_result =
508         GNUNET_OS_check_helper_binary(process_path, GNUNET_NO, NULL);
509     }
510     if(GNUNET_SYSERR == check_result)
511     {
512       GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
513           _("Sensor `%s' process `%s' problem: binary doesn't exist or not executable\n"),
514           sensorinfo->name,
515           sensorinfo->ext_process);
516       set_sensor_enabled(sensorinfo, GNUNET_NO);
517       sensorinfo->running = GNUNET_NO;
518       GNUNET_free(process_path);
519       return;
520     }
521     sensorinfo->ext_cmd_value_received = GNUNET_NO;
522     sensorinfo->ext_cmd = GNUNET_OS_command_run(&sensor_process_callback,
523         sensorinfo,
524         GNUNET_TIME_UNIT_FOREVER_REL,
525         process_path,
526         sensorinfo->ext_process,
527         sensorinfo->ext_args,
528         NULL);
529     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Process started for sensor `%s'\n", sensorinfo->name);
530     GNUNET_free(process_path);
531   }
532   else
533   {
534     sensorinfo->running = GNUNET_NO;
535     GNUNET_break(0); //shouldn't happen
536   }
537 }
538
539 /**
540  * Starts the execution of a sensor
541  *
542  * @param cls unused
543  * @param key hash of sensor name, key to hashmap (unused)
544  * @param value a `struct GNUNET_SENSOR_SensorInfo *`
545  * @return #GNUNET_YES if we should continue to
546  *         iterate,
547  *         #GNUNET_NO if not.
548  */
549 static int
550 schedule_sensor (void *cls, const struct GNUNET_HashCode *key, void *value)
551 {
552   struct GNUNET_SENSOR_SensorInfo *sensorinfo = value;
553
554   if(GNUNET_NO == should_run_sensor(sensorinfo))
555     return GNUNET_YES;
556   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Scheduling sensor `%s' to run after %" PRIu64 " microseconds\n",
557       sensorinfo->name, sensorinfo->interval.rel_value_us);
558   if(GNUNET_SCHEDULER_NO_TASK != sensorinfo->execution_task)
559   {
560     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
561         _("Sensor `%s' execution task already set, this should not happen\n"), sensorinfo->name);
562     return GNUNET_NO;
563   }
564   sensorinfo->execution_task = GNUNET_SCHEDULER_add_delayed(sensorinfo->interval, &sensor_run, sensorinfo);
565   return GNUNET_YES;
566 }
567
568 /**
569  * Starts the execution of all enabled sensors
570  *
571  */
572 static void
573 schedule_all_sensors()
574 {
575   GNUNET_CONTAINER_multihashmap_iterate(sensors, &schedule_sensor, NULL);
576 }
577
578 /**
579  * Process statistics requests.
580  *
581  * @param cls closure
582  * @param server the initialized server
583  * @param c configuration to use
584  */
585 static void
586 run (void *cls,
587      struct GNUNET_SERVER_Handle *server,
588      const struct GNUNET_CONFIGURATION_Handle *c)
589 {
590   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
591     {&handle_get_sensor, NULL, GNUNET_MESSAGE_TYPE_SENSOR_GET,
592      0},
593     {&handle_get_all_sensors, NULL, GNUNET_MESSAGE_TYPE_SENSOR_GETALL,
594      sizeof (struct GNUNET_MessageHeader)},
595     {NULL, NULL, 0, 0}
596   };
597
598   cfg = c;
599   sensors = GNUNET_SENSOR_load_all_sensors ();
600   schedule_all_sensors();
601   SENSOR_analysis_start(c, sensors);
602   SENSOR_reporting_start(c, sensors);
603   SENSOR_update_start (c, sensors);
604   statistics = GNUNET_STATISTICS_create("sensor", cfg);
605   GNUNET_CRYPTO_get_peer_identity(cfg, &peerid);
606   peerstore = GNUNET_PEERSTORE_connect(cfg);
607   GNUNET_SERVER_add_handlers (server, handlers);
608   GNUNET_SERVER_disconnect_notify (server, 
609            &handle_client_disconnect,
610            NULL);
611   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
612         &shutdown_task,
613         NULL);
614 }
615
616
617 /**
618  * The main function for the sensor service.
619  *
620  * @param argc number of arguments from the command line
621  * @param argv command line arguments
622  * @return 0 ok, 1 on error
623  */
624 int
625 main (int argc, char *const *argv)
626 {
627   return (GNUNET_OK ==
628           GNUNET_SERVICE_run (argc,
629                               argv,
630                               "sensor",
631             GNUNET_SERVICE_OPTION_NONE,
632             &run, NULL)) ? 0 : 1;
633 }
634
635 /* end of gnunet-service-sensor.c */