21b8ecd8ab782607ff63a913ff7156c217e3a2ab
[oweals/gnunet.git] / src / statistics / statistics_api.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009 Christian Grothoff (and other contributing authors)
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 2, 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 statistics/statistics_api.c
23  * @brief API of the statistics service
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet_client_lib.h"
28 #include "gnunet_protocols.h"
29 #include "gnunet_server_lib.h"
30 #include "gnunet_statistics_service.h"
31 #include "gnunet_strings_lib.h"
32 #include "statistics.h"
33
34 #define SET_TRANSMIT_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
35
36
37 /**
38  * Types of actions.
39  */
40 enum ActionType
41 {
42   ACTION_GET,
43   ACTION_SET,
44   ACTION_UPDATE
45 };
46
47
48 /**
49  * Linked list of things we still need to do.
50  */
51 struct ActionItem
52 {
53   /**
54    * This is a linked list.
55    */
56   struct ActionItem *next;
57
58   /**
59    * What subsystem is this action about? (can be NULL)
60    */
61   char *subsystem;
62
63   /**
64    * What value is this action about? (can be NULL)
65    */
66   char *name;
67
68   /**
69    * Continuation to call once action is complete.
70    */
71   GNUNET_STATISTICS_Callback cont;
72
73   /**
74    * Function to call (for GET actions only).
75    */
76   GNUNET_STATISTICS_Iterator proc;
77
78   /**
79    * Closure for proc and cont.
80    */
81   void *cls;
82
83   /**
84    * Timeout for this action.
85    */
86   struct GNUNET_TIME_Absolute timeout;
87
88   /**
89    * Associated value.
90    */
91   uint64_t value;
92
93   /**
94    * Flag for SET/UPDATE actions.
95    */
96   int make_persistent;
97
98   /**
99    * Has the current iteration been aborted; for GET actions.
100    */
101   int aborted;
102
103   /**
104    * Is this a GET, SET or UPDATE?
105    */
106   enum ActionType type;
107
108   /**
109    * Size of the message that we will be transmitting.
110    */
111   uint16_t msize;
112
113 };
114
115
116 /**
117  * Handle for the service.
118  */
119 struct GNUNET_STATISTICS_Handle
120 {
121   /**
122    * Our scheduler.
123    */
124   struct GNUNET_SCHEDULER_Handle *sched;
125
126   /**
127    * Name of our subsystem.
128    */
129   char *subsystem;
130
131   /**
132    * Configuration to use.
133    */
134   const struct GNUNET_CONFIGURATION_Handle *cfg;
135
136   /**
137    * Socket (if available).
138    */
139   struct GNUNET_CLIENT_Connection *client;
140
141   /**
142    * Head of the linked list of pending actions (first action
143    * to be performed).
144    */
145   struct ActionItem *action_head;
146
147   /**
148    * Tail of the linked list of actions (for fast append).
149    */
150   struct ActionItem *action_tail;
151
152   /**
153    * Action we are currently busy with (action request has been
154    * transmitted, we're now receiving the response from the
155    * service).
156    */
157   struct ActionItem *current;
158
159   /**
160    * Should this handle be destroyed once we've processed
161    * all actions?
162    */
163   int do_destroy;
164
165 };
166
167
168 /**
169  * Try to (re)connect to the statistics service.
170  *
171  * @return GNUNET_YES on success, GNUNET_NO on failure.
172  */
173 static int
174 try_connect (struct GNUNET_STATISTICS_Handle *ret)
175 {
176   if (ret->client != NULL)
177     return GNUNET_OK;
178   ret->client = GNUNET_CLIENT_connect (ret->sched, "statistics", ret->cfg);
179   if (ret->client != NULL)
180     return GNUNET_YES;
181 #if DEBUG_STATISTICS
182   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
183               _("Failed to connect to statistics service!\n"));
184 #endif
185   return GNUNET_NO;
186 }
187
188
189 /**
190  * Free memory associated with the given action item.
191  */
192 static void
193 free_action_item (struct ActionItem *ai)
194 {
195   GNUNET_free_non_null (ai->subsystem);
196   GNUNET_free_non_null (ai->name);
197   GNUNET_free (ai);
198 }
199
200
201 /**
202  * Get handle for the statistics service.
203  *
204  * @param sched scheduler to use
205  * @param subsystem name of subsystem using the service
206  * @param cfg services configuration in use
207  * @return handle to use
208  */
209 struct GNUNET_STATISTICS_Handle *
210 GNUNET_STATISTICS_create (struct GNUNET_SCHEDULER_Handle *sched,
211                           const char *subsystem,
212                           const struct GNUNET_CONFIGURATION_Handle *cfg)
213 {
214   struct GNUNET_STATISTICS_Handle *ret;
215
216   GNUNET_assert (subsystem != NULL);
217   GNUNET_assert (sched != NULL);
218   GNUNET_assert (cfg != NULL);
219   ret = GNUNET_malloc (sizeof (struct GNUNET_STATISTICS_Handle));
220   ret->sched = sched;
221   ret->cfg = cfg;
222   ret->subsystem = GNUNET_strdup (subsystem);
223   try_connect (ret);
224   return ret;
225 }
226
227
228 /**
229  * Actually free the handle.
230  */
231 static void
232 do_destroy (struct GNUNET_STATISTICS_Handle *h)
233 {
234   GNUNET_assert (h->action_head == NULL);
235   GNUNET_assert (h->current == NULL);
236   if (h->client != NULL)
237     {
238       GNUNET_CLIENT_disconnect (h->client);
239       h->client = NULL;
240     }
241   GNUNET_free (h->subsystem);
242   GNUNET_free (h);
243 }
244
245
246 /**
247  * Destroy a handle (free all state associated with
248  * it).
249  */
250 void
251 GNUNET_STATISTICS_destroy (struct GNUNET_STATISTICS_Handle *handle)
252 {
253   GNUNET_assert (handle->do_destroy == GNUNET_NO);
254   if ((handle->action_head != NULL) || (handle->current != NULL))
255     {
256       handle->do_destroy = GNUNET_YES;
257       return;
258     }
259   do_destroy (handle);
260 }
261
262
263 /**
264  * Process the message.
265  *
266  * @return GNUNET_OK if the message was well-formed
267  */
268 static int
269 process_message (struct GNUNET_STATISTICS_Handle *h,
270                  const struct GNUNET_MessageHeader *msg)
271 {
272   char *service;
273   char *name;
274   const struct GNUNET_STATISTICS_ReplyMessage *smsg;
275   uint16_t size;
276
277   if (h->current->aborted)
278     return GNUNET_OK;           /* don't bother */
279   size = ntohs (msg->size);
280   if (size < sizeof (struct GNUNET_STATISTICS_ReplyMessage))
281     {
282       GNUNET_break (0);
283       return GNUNET_SYSERR;
284     }
285   smsg = (const struct GNUNET_STATISTICS_ReplyMessage *) msg;
286   size -= sizeof (struct GNUNET_STATISTICS_ReplyMessage);
287   if (size != GNUNET_STRINGS_buffer_tokenize ((const char *) &smsg[1],
288                                               size, 2, &service, &name))
289     {
290       GNUNET_break (0);
291       return GNUNET_SYSERR;
292     }
293 #if DEBUG_STATISTICS
294   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
295               "Received valid statistic on `%s:%s': %llu\n",
296               service, name, GNUNET_ntohll (smsg->value));
297 #endif
298   if (GNUNET_OK !=
299       h->current->proc (h->current->cls,
300                         service,
301                         name,
302                         GNUNET_ntohll (smsg->value),
303                         0 !=
304                         (ntohl (smsg->uid) & GNUNET_STATISTICS_PERSIST_BIT)))
305     {
306 #if DEBUG_STATISTICS
307       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
308                   "Processing of remaining statistics aborted by client.\n");
309 #endif
310       h->current->aborted = GNUNET_YES;
311     }
312   return GNUNET_OK;
313 }
314
315
316
317 /**
318  * Schedule the next action to be performed.
319  */
320 static void schedule_action (struct GNUNET_STATISTICS_Handle *h);
321
322
323 /**
324  * GET processing is complete, tell client about it.
325  */
326 static void
327 finish (struct GNUNET_STATISTICS_Handle *h, int code)
328 {
329   struct ActionItem *pos = h->current;
330   h->current = NULL;
331   schedule_action (h);
332   if (pos->cont != NULL)
333     pos->cont (pos->cls, code);
334   free_action_item (pos);
335 }
336
337
338 /**
339  * Function called with messages from stats service.
340  *
341  * @param cls closure
342  * @param msg message received, NULL on timeout or fatal error
343  */
344 static void
345 receive_stats (void *cls, const struct GNUNET_MessageHeader *msg)
346 {
347   struct GNUNET_STATISTICS_Handle *h = cls;
348
349   if (msg == NULL)
350     {
351       GNUNET_CLIENT_disconnect (h->client);
352       h->client = NULL;
353 #if DEBUG_STATISTICS
354       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
355                   "Error receiving statistics from service, is the service running?\n" );
356 #endif
357       finish (h, GNUNET_SYSERR);
358       return;
359     }
360   switch (ntohs (msg->type))
361     {
362     case GNUNET_MESSAGE_TYPE_STATISTICS_END:
363 #if DEBUG_STATISTICS
364       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
365                   "Received end of statistics marker\n");
366 #endif
367       finish (h, GNUNET_OK);
368       return;
369     case GNUNET_MESSAGE_TYPE_STATISTICS_VALUE:
370       if (GNUNET_OK == process_message (h, msg))
371         {
372           /* finally, look for more! */
373           GNUNET_CLIENT_receive (h->client,
374                                  &receive_stats,
375                                  h,
376                                  GNUNET_TIME_absolute_get_remaining
377                                  (h->current->timeout));
378           return;
379         }
380       GNUNET_break (0);
381       break;
382     default:
383       GNUNET_break (0);
384       break;
385     }
386   GNUNET_CLIENT_disconnect (h->client);
387   h->client = NULL;
388   finish (h, GNUNET_SYSERR);
389 }
390
391
392 /**
393  * Transmit a GET request (and if successful, start to receive
394  * the response).
395  */
396 static size_t
397 transmit_get (struct GNUNET_STATISTICS_Handle *handle, size_t size, void *buf)
398 {
399   struct GNUNET_MessageHeader *hdr;
400   size_t slen1;
401   size_t slen2;
402   uint16_t msize;
403
404   if (buf == NULL)
405     {
406       /* timeout / error */
407 #if DEBUG_STATISTICS
408       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
409                   "Transmission of request for statistics failed!\n");
410 #endif
411       finish (handle, GNUNET_SYSERR);
412       return 0;
413     }
414   slen1 = strlen (handle->current->subsystem) + 1;
415   slen2 = strlen (handle->current->name) + 1;
416   msize = slen1 + slen2 + sizeof (struct GNUNET_MessageHeader);
417   GNUNET_assert (msize <= size);
418   hdr = (struct GNUNET_MessageHeader *) buf;
419   hdr->size = htons (msize);
420   hdr->type = htons (GNUNET_MESSAGE_TYPE_STATISTICS_GET);
421   GNUNET_assert (slen1 + slen2 ==
422                  GNUNET_STRINGS_buffer_fill ((char *) &hdr[1],
423                                              slen1 + slen2,
424                                              2,
425                                              handle->current->subsystem,
426                                              handle->current->name));
427   GNUNET_CLIENT_receive (handle->client,
428                          &receive_stats,
429                          handle,
430                          GNUNET_TIME_absolute_get_remaining (handle->
431                                                              current->timeout));
432   return msize;
433 }
434
435
436
437 /**
438  * Transmit a SET/UPDATE request.
439  */
440 static size_t
441 transmit_set (struct GNUNET_STATISTICS_Handle *handle, size_t size, void *buf)
442 {
443   struct GNUNET_STATISTICS_SetMessage *r;
444   size_t slen;
445   size_t nlen;
446   size_t nsize;
447
448   if (NULL == buf)
449     {
450       finish (handle, GNUNET_SYSERR);
451       return 0;
452     }
453
454   slen = strlen (handle->current->subsystem) + 1;
455   nlen = strlen (handle->current->name) + 1;
456   nsize = sizeof (struct GNUNET_STATISTICS_SetMessage) + slen + nlen;
457   if (size < nsize)
458     {
459       GNUNET_break (0);
460       finish (handle, GNUNET_SYSERR);
461       return 0;
462     }
463   r = buf;
464   r->header.size = htons (nsize);
465   r->header.type = htons (GNUNET_MESSAGE_TYPE_STATISTICS_SET);
466   r->flags = 0;
467   r->value = GNUNET_htonll (handle->current->value);
468   if (handle->current->make_persistent)
469     r->flags |= htonl (GNUNET_STATISTICS_SETFLAG_PERSISTENT);
470   if (handle->current->type == ACTION_UPDATE)
471     r->flags |= htonl (GNUNET_STATISTICS_SETFLAG_RELATIVE);
472   GNUNET_assert (slen + nlen ==
473                  GNUNET_STRINGS_buffer_fill ((char *) &r[1],
474                                              slen + nlen,
475                                              2,
476                                              handle->current->subsystem,
477                                              handle->current->name));
478   finish (handle, GNUNET_OK);
479   return nsize;
480 }
481
482
483 static size_t
484 transmit_action (void *cls, size_t size, void *buf)
485 {
486   struct GNUNET_STATISTICS_Handle *handle = cls;
487   size_t ret;
488
489   switch (handle->current->type)
490     {
491     case ACTION_GET:
492       ret = transmit_get (handle, size, buf);
493       break;
494     case ACTION_SET:
495     case ACTION_UPDATE:
496       ret = transmit_set (handle, size, buf);
497       break;
498     default:
499       ret = 0;
500       GNUNET_break (0);
501       break; 
502     }
503   return ret;
504 }
505
506
507 /**
508  * Schedule the next action to be performed.
509  */
510 static void
511 schedule_action (struct GNUNET_STATISTICS_Handle *h)
512 {
513   struct GNUNET_TIME_Relative timeout;
514
515   if (h->current != NULL)
516     return;                     /* action already pending */
517   if (GNUNET_YES != try_connect (h))
518     {
519       finish (h, GNUNET_SYSERR);
520       return;
521     }
522
523   /* schedule next action */
524   h->current = h->action_head;
525   if (NULL == h->current)
526     {
527       /* no pending network action, check destroy! */
528       if (h->do_destroy != GNUNET_YES)
529         return;
530       do_destroy (h);
531       return;
532     }
533   h->action_head = h->action_head->next;
534   if (NULL == h->action_head)
535     h->action_tail = NULL;
536   h->current->next = NULL;
537
538   timeout = GNUNET_TIME_absolute_get_remaining (h->current->timeout);
539   if (NULL ==
540       GNUNET_CLIENT_notify_transmit_ready (h->client,
541                                            h->current->msize,
542                                            timeout, &transmit_action, h))
543     {
544 #if DEBUG_STATISTICS
545       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
546                   "Failed to transmit request to statistics service.\n");
547 #endif
548       finish (h, GNUNET_SYSERR);
549     }
550 }
551
552
553 static void
554 insert_ai (struct GNUNET_STATISTICS_Handle *h, struct ActionItem *ai)
555 {
556   if (h->action_tail == NULL)
557     {
558       h->action_head = ai;
559       h->action_tail = ai;
560       schedule_action (h);
561     }
562   else
563     {
564       h->action_tail->next = ai;
565       h->action_tail = ai;
566     }
567 }
568
569
570 /**
571  * Get statistic from the peer.
572  *
573  * @param handle identification of the statistics service
574  * @param subsystem limit to the specified subsystem, NULL for our subsystem
575  * @param name name of the statistic value, NULL for all values
576  * @param timeout after how long should we give up (and call
577  *        cont with an error code)?
578  * @param cont continuation to call when done (can be NULL)
579  * @param proc function to call on each value
580  * @param cls closure for cont and proc
581  */
582 void
583 GNUNET_STATISTICS_get (struct GNUNET_STATISTICS_Handle *handle,
584                        const char *subsystem,
585                        const char *name,
586                        struct GNUNET_TIME_Relative timeout,
587                        GNUNET_STATISTICS_Callback cont,
588                        GNUNET_STATISTICS_Iterator proc, void *cls)
589 {
590   size_t slen1;
591   size_t slen2;
592   struct ActionItem *ai;
593
594   GNUNET_assert (handle != NULL);
595   GNUNET_assert (proc != NULL);
596   if (GNUNET_YES != try_connect (handle))
597     {
598 #if DEBUG_STATISTICS
599       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
600                   "Failed to connect to statistics service, can not get value `%s:%s'.\n",
601                   strlen (subsystem) ? subsystem : "*",
602                   strlen (name) ? name : "*");
603 #endif
604       if (cont != NULL)
605         cont (cls, GNUNET_SYSERR);
606       return;
607     }
608   if (subsystem == NULL)
609     subsystem = "";
610   if (name == NULL)
611     name = "";
612   slen1 = strlen (subsystem);
613   slen2 = strlen (name);
614   GNUNET_assert (slen1 + slen2 + sizeof (struct GNUNET_MessageHeader) <
615                  GNUNET_SERVER_MAX_MESSAGE_SIZE);
616   ai = GNUNET_malloc (sizeof (struct ActionItem));
617   ai->subsystem = GNUNET_strdup (subsystem);
618   ai->name = GNUNET_strdup (name);
619   ai->cont = cont;
620   ai->proc = proc;
621   ai->cls = cls;
622   ai->timeout = GNUNET_TIME_relative_to_absolute (timeout);
623   ai->type = ACTION_GET;
624   ai->msize = slen1 + slen2 + sizeof (struct GNUNET_MessageHeader);
625   insert_ai (handle, ai);
626 }
627
628
629 static void
630 add_setter_action (struct GNUNET_STATISTICS_Handle *h,
631                    const char *name,
632                    int make_persistent,
633                    uint64_t value, enum ActionType type)
634 {
635   struct ActionItem *ai;
636   size_t slen;
637   size_t nlen;
638   size_t nsize;
639
640   GNUNET_assert (h != NULL);
641   GNUNET_assert (name != NULL);
642   if (GNUNET_YES != try_connect (h))
643     return;
644   slen = strlen (h->subsystem) + 1;
645   nlen = strlen (name) + 1;
646   nsize = sizeof (struct GNUNET_STATISTICS_SetMessage) + slen + nlen;
647   if (nsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
648     {
649       GNUNET_break (0);
650       return;
651     }
652   ai = GNUNET_malloc (sizeof (struct ActionItem));
653   ai->subsystem = GNUNET_strdup (h->subsystem);
654   ai->name = GNUNET_strdup (name);
655   ai->timeout = GNUNET_TIME_relative_to_absolute (SET_TRANSMIT_TIMEOUT);
656   ai->make_persistent = make_persistent;
657   ai->msize = nsize;
658   ai->value = value;
659   ai->type = type;
660   insert_ai (h, ai);
661   schedule_action (h);
662 }
663
664
665 /**
666  * Set statistic value for the peer.  Will always use our
667  * subsystem (the argument used when "handle" was created).
668  *
669  * @param handle identification of the statistics service
670  * @param name name of the statistic value
671  * @param value new value to set
672  * @param make_persistent should the value be kept across restarts?
673  */
674 void
675 GNUNET_STATISTICS_set (struct GNUNET_STATISTICS_Handle *handle,
676                        const char *name,
677                        uint64_t value, int make_persistent)
678 {
679   add_setter_action (handle, name, make_persistent, value, ACTION_SET);
680 }
681
682
683 /**
684  * Set statistic value for the peer.  Will always use our
685  * subsystem (the argument used when "handle" was created).
686  *
687  * @param handle identification of the statistics service
688  * @param name name of the statistic value
689  * @param delta change in value (added to existing value)
690  * @param make_persistent should the value be kept across restarts?
691  */
692 void
693 GNUNET_STATISTICS_update (struct GNUNET_STATISTICS_Handle *handle,
694                           const char *name,
695                           int64_t delta, int make_persistent)
696 {
697   add_setter_action (handle, name, make_persistent,
698                      (unsigned long long) delta, ACTION_UPDATE);
699 }
700
701
702 /* end of statistics_api.c */