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