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 int add_sensor_to_tc (void *cls,
216                       const struct GNUNET_HashCode *key,
217                       void *value)
218 {
219   struct GNUNET_SERVER_TransmitContext *tc = cls;
220   struct GNUNET_SENSOR_SensorInfo *sensorinfo = value;
221   struct SensorInfoMessage *msg;
222
223   msg = create_sensor_info_msg(sensorinfo);
224   GNUNET_SERVER_transmit_context_append_message(tc, (struct GNUNET_MessageHeader *)msg);
225
226   GNUNET_free(msg);
227
228   return GNUNET_YES;
229 }
230
231 /**
232  * Handle GET ALL SENSORS message.
233  *
234  * @param cls closure
235  * @param client identification of the client
236  * @param message the actual message
237  */
238 static void
239 handle_get_all_sensors (void *cls, struct GNUNET_SERVER_Client *client,
240             const struct GNUNET_MessageHeader *message)
241 {
242   struct GNUNET_SERVER_TransmitContext *tc;
243
244   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "`%s' message received.\n",
245                 "GET ALL SENSOR");
246   tc = GNUNET_SERVER_transmit_context_create (client);
247   GNUNET_CONTAINER_multihashmap_iterate(sensors, &add_sensor_to_tc, tc);
248   GNUNET_SERVER_transmit_context_append_data(tc, NULL, 0, GNUNET_MESSAGE_TYPE_SENSOR_END);
249   GNUNET_SERVER_transmit_context_run (tc, GNUNET_TIME_UNIT_FOREVER_REL);
250 }
251
252 /**
253  * Do a series of checks to determine if sensor should execute
254  *
255  * @return #GNUNET_YES / #GNUNET_NO
256  */
257 static int
258 should_run_sensor(struct GNUNET_SENSOR_SensorInfo *sensorinfo)
259 {
260   struct GNUNET_TIME_Absolute now;
261
262   if(GNUNET_NO == sensorinfo->enabled)
263   {
264     GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Sensor `%s' is disabled, will not run\n", sensorinfo->name);
265     return GNUNET_NO;
266   }
267   now = GNUNET_TIME_absolute_get();
268   if(NULL != sensorinfo->start_time
269       && now.abs_value_us < sensorinfo->start_time->abs_value_us)
270   {
271     GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Start time for sensor `%s' not reached yet, will not run\n", sensorinfo->name);
272     return GNUNET_NO;
273   }
274   if(NULL != sensorinfo->end_time
275       && now.abs_value_us >= sensorinfo->end_time->abs_value_us)
276   {
277     GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Sensor `%s' expired, disabling.\n", sensorinfo->name);
278     set_sensor_enabled(sensorinfo, GNUNET_NO);
279     return GNUNET_NO;
280   }
281   return GNUNET_YES;
282 }
283
284 /**
285  * Callback function to process statistic values
286  *
287  * @param cls `struct GNUNET_SENSOR_SensorInfo *`
288  * @param subsystem name of subsystem that created the statistic
289  * @param name the name of the datum
290  * @param value the current value
291  * @param is_persistent #GNUNET_YES if the value is persistent, #GNUNET_NO if not
292  * @return #GNUNET_OK to continue, #GNUNET_SYSERR to abort iteration
293  */
294 int sensor_statistics_iterator (void *cls,
295     const char *ss,
296     const char *name,
297     uint64_t value,
298     int is_persistent)
299 {
300   struct GNUNET_SENSOR_SensorInfo *sensorinfo = cls;
301   double dvalue = (double)value;
302   struct GNUNET_TIME_Absolute expiry;
303
304   GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Received a value for sensor `%s': %" PRIu64 "\n", sensorinfo->name, value);
305   expiry = GNUNET_TIME_relative_to_absolute(sensorinfo->lifetime);
306   GNUNET_PEERSTORE_store(peerstore,
307       subsystem,
308       &peerid,
309       sensorinfo->name,
310       &dvalue,
311       sizeof(dvalue),
312       expiry,
313       GNUNET_PEERSTORE_STOREOPTION_MULTIPLE,
314       NULL,
315       NULL);
316   return GNUNET_SYSERR; /* We only want one value */
317 }
318
319 /**
320  * Continuation called after sensor gets all gnunet statistics values
321  *
322  * @param cls `struct GNUNET_SENSOR_SensorInfo *`
323  * @param success #GNUNET_OK if statistics were
324  *        successfully obtained, #GNUNET_SYSERR if not.
325  */
326 void end_sensor_run_stat (void *cls, int success)
327 {
328   struct GNUNET_SENSOR_SensorInfo *sensorinfo = cls;
329
330   sensorinfo->gnunet_stat_get_handle = NULL;
331   sensorinfo->running = GNUNET_NO;
332 }
333
334 /**
335  * Tries to parse a received sensor value to its
336  * expected datatype
337  *
338  * @param value the string value received, should be null terminated
339  * @param sensor sensor information struct
340  * @param ret pointer to parsed value
341  * @return size of new parsed value, 0 for error
342  */
343 static size_t
344 parse_sensor_value (const char *value,
345                     struct GNUNET_SENSOR_SensorInfo *sensor,
346                     void **ret)
347 {
348   double *dval;
349   char *endptr;
350
351   *ret = NULL;
352   if ('\0' == *value)
353     return 0;
354   if(0 == strcmp("numeric", sensor->expected_datatype))
355   {
356     dval = GNUNET_new(double);
357     *dval = strtod(value, &endptr);
358     if(value == endptr)
359       return 0;
360    *ret = dval;
361    return sizeof(double);
362   }
363   if(0 == strcmp("string", sensor->expected_datatype))
364   {
365     *ret = GNUNET_strdup(value);
366     return strlen(value) + 1;
367   }
368   GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
369       _("Unknown value type expected by sensor, this should not happen.\n"));
370   return 0;
371 }
372
373 /**
374  * Callback for output of executed sensor process
375  *
376  * @param cls `struct GNUNET_SENSOR_SensorInfo *`
377  * @param line line of output from a command, NULL for the end
378  */
379 void sensor_process_callback (void *cls, const char *line)
380 {
381   struct GNUNET_SENSOR_SensorInfo *sensorinfo = cls;
382   void *value;
383   size_t valsize;
384   struct GNUNET_TIME_Absolute expiry;
385
386   if(NULL == line)
387   {
388     GNUNET_OS_command_stop(sensorinfo->ext_cmd);
389     sensorinfo->ext_cmd = NULL;
390     sensorinfo->running = GNUNET_NO;
391     sensorinfo->ext_cmd_value_received = GNUNET_NO;
392     return;
393   }
394   if(GNUNET_YES == sensorinfo->ext_cmd_value_received)
395     return; /* We only want one *valid* value */
396   GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Received a value for sensor `%s': %s\n", sensorinfo->name, line);
397   valsize = parse_sensor_value(line, sensorinfo, &value);
398   if (valsize == 0) /* invalid value, FIXME: should we disable the sensor now? */
399   {
400     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
401         _("Received an invalid value for sensor `%s': %s\n"),
402         sensorinfo->name, line);
403   }
404   else
405   {
406     sensorinfo->ext_cmd_value_received = GNUNET_YES;
407     expiry = GNUNET_TIME_relative_to_absolute(sensorinfo->lifetime);
408     GNUNET_PEERSTORE_store(peerstore,
409         subsystem,
410         &peerid,
411         sensorinfo->name,
412         value,
413         valsize,
414         expiry,
415         GNUNET_PEERSTORE_STOREOPTION_MULTIPLE,
416         NULL,
417         NULL);
418     GNUNET_free (value);
419   }
420 }
421
422 /**
423  * Checks if the given file is a path
424  *
425  * @return #GNUNET_YES / #GNUNET_NO
426  */
427 static int
428 is_path(char *filename)
429 {
430   size_t filename_len;
431   int i;
432
433   filename_len = strlen(filename);
434   for(i = 0; i < filename_len; i++)
435   {
436     if(DIR_SEPARATOR == filename[i])
437       return GNUNET_YES;
438   }
439   return GNUNET_NO;
440 }
441
442 /**
443  * Actual execution of a sensor
444  *
445  * @param cls 'struct SensorInfo'
446  * @param tc unsed
447  */
448 void
449 sensor_run (void *cls,
450     const struct GNUNET_SCHEDULER_TaskContext * tc)
451 {
452   struct GNUNET_SENSOR_SensorInfo *sensorinfo = cls;
453   int check_result;
454   char *sensors_dir;
455   char *process_path;
456
457   sensorinfo->execution_task = GNUNET_SCHEDULER_add_delayed(sensorinfo->interval, &sensor_run, sensorinfo);
458   if(GNUNET_YES == sensorinfo->running) //FIXME: should we try to kill?
459   {
460     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Sensor `%s' running for too long, will try again next interval\n", sensorinfo->name);
461     return;
462   }
463   if(GNUNET_NO == should_run_sensor(sensorinfo))
464     return;
465   sensorinfo->running = GNUNET_YES;
466   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Starting the execution of sensor `%s'\n", sensorinfo->name);
467   if(0 == strcmp ("gnunet-statistics", sensorinfo->source))
468   {
469     sensorinfo->gnunet_stat_get_handle = GNUNET_STATISTICS_get(statistics,
470         sensorinfo->gnunet_stat_service,
471         sensorinfo->gnunet_stat_name,
472         sensorinfo->interval, //try to get values only for the interval of the sensor
473         &end_sensor_run_stat,
474         &sensor_statistics_iterator,
475         sensorinfo);
476   }
477   else if(0 == strcmp ("process", sensorinfo->source))
478   {
479     if(GNUNET_YES == is_path(sensorinfo->ext_process))
480     {
481       GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
482           _("Sensor `%s': External process should not be a path, disabling sensor.\n"),
483           sensorinfo->name);
484       set_sensor_enabled(sensorinfo, GNUNET_NO);
485       return;
486     }
487     //check if the process exists in $PATH
488     process_path = GNUNET_strdup(sensorinfo->ext_process);
489     check_result =
490         GNUNET_OS_check_helper_binary(process_path, GNUNET_NO, NULL);
491     if(GNUNET_SYSERR == check_result)
492     {
493       //search in sensor directory
494       sensors_dir = GNUNET_SENSOR_get_sensor_dir ();
495       GNUNET_free(process_path);
496       GNUNET_asprintf(&process_path, "%s%s-files%s%s",
497           sensors_dir,
498           sensorinfo->name,
499           DIR_SEPARATOR_STR,
500           sensorinfo->ext_process);
501       GNUNET_free(sensors_dir);
502       check_result =
503         GNUNET_OS_check_helper_binary(process_path, GNUNET_NO, NULL);
504     }
505     if(GNUNET_SYSERR == check_result)
506     {
507       GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
508           _("Sensor `%s' process `%s' problem: binary doesn't exist or not executable\n"),
509           sensorinfo->name,
510           sensorinfo->ext_process);
511       set_sensor_enabled(sensorinfo, GNUNET_NO);
512       sensorinfo->running = GNUNET_NO;
513       GNUNET_free(process_path);
514       return;
515     }
516     sensorinfo->ext_cmd_value_received = GNUNET_NO;
517     sensorinfo->ext_cmd = GNUNET_OS_command_run(&sensor_process_callback,
518         sensorinfo,
519         GNUNET_TIME_UNIT_FOREVER_REL,
520         process_path,
521         sensorinfo->ext_process,
522         sensorinfo->ext_args,
523         NULL);
524     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Process started for sensor `%s'\n", sensorinfo->name);
525     GNUNET_free(process_path);
526   }
527   else
528   {
529     sensorinfo->running = GNUNET_NO;
530     GNUNET_break(0); //shouldn't happen
531   }
532 }
533
534 /**
535  * Starts the execution of a sensor
536  *
537  * @param cls unused
538  * @param key hash of sensor name, key to hashmap (unused)
539  * @param value a `struct GNUNET_SENSOR_SensorInfo *`
540  * @return #GNUNET_YES if we should continue to
541  *         iterate,
542  *         #GNUNET_NO if not.
543  */
544 int schedule_sensor(void *cls,
545     const struct GNUNET_HashCode *key, void *value)
546 {
547   struct GNUNET_SENSOR_SensorInfo *sensorinfo = value;
548
549   if(GNUNET_NO == should_run_sensor(sensorinfo))
550     return GNUNET_YES;
551   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Scheduling sensor `%s' to run after %" PRIu64 " microseconds\n",
552       sensorinfo->name, sensorinfo->interval.rel_value_us);
553   if(GNUNET_SCHEDULER_NO_TASK != sensorinfo->execution_task)
554   {
555     GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
556         _("Sensor `%s' execution task already set, this should not happen\n"), sensorinfo->name);
557     return GNUNET_NO;
558   }
559   sensorinfo->execution_task = GNUNET_SCHEDULER_add_delayed(sensorinfo->interval, &sensor_run, sensorinfo);
560   return GNUNET_YES;
561 }
562
563 /**
564  * Starts the execution of all enabled sensors
565  *
566  */
567 static void
568 schedule_all_sensors()
569 {
570   GNUNET_CONTAINER_multihashmap_iterate(sensors, &schedule_sensor, NULL);
571 }
572
573 /**
574  * Process statistics requests.
575  *
576  * @param cls closure
577  * @param server the initialized server
578  * @param c configuration to use
579  */
580 static void
581 run (void *cls,
582      struct GNUNET_SERVER_Handle *server,
583      const struct GNUNET_CONFIGURATION_Handle *c)
584 {
585   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
586     {&handle_get_sensor, NULL, GNUNET_MESSAGE_TYPE_SENSOR_GET,
587      0},
588     {&handle_get_all_sensors, NULL, GNUNET_MESSAGE_TYPE_SENSOR_GETALL,
589      sizeof (struct GNUNET_MessageHeader)},
590     {NULL, NULL, 0, 0}
591   };
592
593   cfg = c;
594   sensors = GNUNET_SENSOR_load_all_sensors ();
595   schedule_all_sensors();
596   SENSOR_analysis_start(c, sensors);
597   SENSOR_reporting_start(c, sensors);
598   SENSOR_update_start (c, sensors);
599   statistics = GNUNET_STATISTICS_create("sensor", cfg);
600   GNUNET_CRYPTO_get_peer_identity(cfg, &peerid);
601   peerstore = GNUNET_PEERSTORE_connect(cfg);
602   GNUNET_SERVER_add_handlers (server, handlers);
603   GNUNET_SERVER_disconnect_notify (server, 
604            &handle_client_disconnect,
605            NULL);
606   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
607         &shutdown_task,
608         NULL);
609 }
610
611
612 /**
613  * The main function for the sensor service.
614  *
615  * @param argc number of arguments from the command line
616  * @param argv command line arguments
617  * @return 0 ok, 1 on error
618  */
619 int
620 main (int argc, char *const *argv)
621 {
622   return (GNUNET_OK ==
623           GNUNET_SERVICE_run (argc,
624                               argv,
625                               "sensor",
626             GNUNET_SERVICE_OPTION_NONE,
627             &run, NULL)) ? 0 : 1;
628 }
629
630 /* end of gnunet-service-sensor.c */