9606d20d1460246cae4261c152e2d2f8bcf7f1f7
[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    * Currently pending transmission request.
143    */
144   struct GNUNET_CLIENT_TransmitHandle *th;
145
146   /**
147    * Head of the linked list of pending actions (first action
148    * to be performed).
149    */
150   struct ActionItem *action_head;
151
152   /**
153    * Tail of the linked list of actions (for fast append).
154    */
155   struct ActionItem *action_tail;
156
157   /**
158    * Action we are currently busy with (action request has been
159    * transmitted, we're now receiving the response from the
160    * service).
161    */
162   struct ActionItem *current;
163
164   /**
165    * Should this handle auto-destruct once all actions have
166    * been processed?
167    */
168   int do_destroy;
169
170 };
171
172
173 /**
174  * Try to (re)connect to the statistics service.
175  *
176  * @return GNUNET_YES on success, GNUNET_NO on failure.
177  */
178 static int
179 try_connect (struct GNUNET_STATISTICS_Handle *ret)
180 {
181   if (ret->client != NULL)
182     return GNUNET_OK;
183   ret->client = GNUNET_CLIENT_connect (ret->sched, "statistics", ret->cfg);
184   if (ret->client != NULL)
185     return GNUNET_YES;
186 #if DEBUG_STATISTICS
187   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
188               _("Failed to connect to statistics service!\n"));
189 #endif
190   return GNUNET_NO;
191 }
192
193
194 /**
195  * Free memory associated with the given action item.
196  */
197 static void
198 free_action_item (struct ActionItem *ai)
199 {
200   GNUNET_free_non_null (ai->subsystem);
201   GNUNET_free_non_null (ai->name);
202   GNUNET_free (ai);
203 }
204
205
206
207
208
209 /**
210  * Schedule the next action to be performed.
211  */
212 static void schedule_action (struct GNUNET_STATISTICS_Handle *h);
213
214
215 /**
216  * GET processing is complete, tell client about it.
217  */
218 static void
219 finish (struct GNUNET_STATISTICS_Handle *h, int code)
220 {
221   struct ActionItem *pos = h->current;
222   h->current = NULL;
223   schedule_action (h);
224   if (pos->cont != NULL)
225     pos->cont (pos->cls, code);
226   free_action_item (pos);
227 }
228
229
230 /**
231  * Process the message.
232  *
233  * @return GNUNET_OK if the message was well-formed
234  */
235 static int
236 process_message (struct GNUNET_STATISTICS_Handle *h,
237                  const struct GNUNET_MessageHeader *msg)
238 {
239   char *service;
240   char *name;
241   const struct GNUNET_STATISTICS_ReplyMessage *smsg;
242   uint16_t size;
243
244   if (h->current->aborted)
245     return GNUNET_OK;           /* don't bother */
246   size = ntohs (msg->size);
247   if (size < sizeof (struct GNUNET_STATISTICS_ReplyMessage))
248     {
249       GNUNET_break (0);
250       return GNUNET_SYSERR;
251     }
252   smsg = (const struct GNUNET_STATISTICS_ReplyMessage *) msg;
253   size -= sizeof (struct GNUNET_STATISTICS_ReplyMessage);
254   if (size != GNUNET_STRINGS_buffer_tokenize ((const char *) &smsg[1],
255                                               size, 2, &service, &name))
256     {
257       GNUNET_break (0);
258       return GNUNET_SYSERR;
259     }
260 #if DEBUG_STATISTICS
261   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
262               "Received valid statistic on `%s:%s': %llu\n",
263               service, name, GNUNET_ntohll (smsg->value));
264 #endif
265   if (GNUNET_OK !=
266       h->current->proc (h->current->cls,
267                         service,
268                         name,
269                         GNUNET_ntohll (smsg->value),
270                         0 !=
271                         (ntohl (smsg->uid) & GNUNET_STATISTICS_PERSIST_BIT)))
272     {
273 #if DEBUG_STATISTICS
274       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
275                   "Processing of remaining statistics aborted by client.\n");
276 #endif
277       h->current->aborted = GNUNET_YES;
278     }
279   return GNUNET_OK;
280 }
281
282
283 /**
284  * Function called with messages from stats service.
285  *
286  * @param cls closure
287  * @param msg message received, NULL on timeout or fatal error
288  */
289 static void
290 receive_stats (void *cls, const struct GNUNET_MessageHeader *msg)
291 {
292   struct GNUNET_STATISTICS_Handle *h = cls;
293
294   if (msg == NULL)
295     {
296       if (NULL != h->client)
297         {
298           GNUNET_CLIENT_disconnect (h->client);
299           h->client = NULL;
300         }
301 #if DEBUG_STATISTICS
302       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
303                   "Error receiving statistics from service, is the service running?\n" );
304 #endif
305       finish (h, GNUNET_SYSERR);
306       return;
307     }
308   switch (ntohs (msg->type))
309     {
310     case GNUNET_MESSAGE_TYPE_STATISTICS_END:
311 #if DEBUG_STATISTICS
312       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
313                   "Received end of statistics marker\n");
314 #endif
315       finish (h, GNUNET_OK);
316       return;
317     case GNUNET_MESSAGE_TYPE_STATISTICS_VALUE:
318       if (GNUNET_OK == process_message (h, msg))
319         {
320           /* finally, look for more! */
321           GNUNET_CLIENT_receive (h->client,
322                                  &receive_stats,
323                                  h,
324                                  GNUNET_TIME_absolute_get_remaining
325                                  (h->current->timeout));
326           return;
327         }
328       GNUNET_break (0);
329       break;
330     default:
331       GNUNET_break (0);
332       break;
333     }
334   if (NULL != h->client)
335     {
336       GNUNET_CLIENT_disconnect (h->client);
337       h->client = NULL;
338     }
339   finish (h, GNUNET_SYSERR);
340 }
341
342
343 /**
344  * Transmit a GET request (and if successful, start to receive
345  * the response).
346  */
347 static size_t
348 transmit_get (struct GNUNET_STATISTICS_Handle *handle, size_t size, void *buf)
349 {
350   struct GNUNET_MessageHeader *hdr;
351   size_t slen1;
352   size_t slen2;
353   uint16_t msize;
354
355   if (buf == NULL)
356     {
357       /* timeout / error */
358 #if DEBUG_STATISTICS
359       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
360                   "Transmission of request for statistics failed!\n");
361 #endif
362       finish (handle, GNUNET_SYSERR);
363       return 0;
364     }
365   slen1 = strlen (handle->current->subsystem) + 1;
366   slen2 = strlen (handle->current->name) + 1;
367   msize = slen1 + slen2 + sizeof (struct GNUNET_MessageHeader);
368   GNUNET_assert (msize <= size);
369   hdr = (struct GNUNET_MessageHeader *) buf;
370   hdr->size = htons (msize);
371   hdr->type = htons (GNUNET_MESSAGE_TYPE_STATISTICS_GET);
372   GNUNET_assert (slen1 + slen2 ==
373                  GNUNET_STRINGS_buffer_fill ((char *) &hdr[1],
374                                              slen1 + slen2,
375                                              2,
376                                              handle->current->subsystem,
377                                              handle->current->name));
378   GNUNET_CLIENT_receive (handle->client,
379                          &receive_stats,
380                          handle,
381                          GNUNET_TIME_absolute_get_remaining (handle->
382                                                              current->timeout));
383   return msize;
384 }
385
386
387
388 /**
389  * Transmit a SET/UPDATE request.
390  */
391 static size_t
392 transmit_set (struct GNUNET_STATISTICS_Handle *handle, size_t size, void *buf)
393 {
394   struct GNUNET_STATISTICS_SetMessage *r;
395   size_t slen;
396   size_t nlen;
397   size_t nsize;
398
399   if (NULL == buf)
400     {
401       finish (handle, GNUNET_SYSERR);
402       return 0;
403     }
404
405   slen = strlen (handle->current->subsystem) + 1;
406   nlen = strlen (handle->current->name) + 1;
407   nsize = sizeof (struct GNUNET_STATISTICS_SetMessage) + slen + nlen;
408   if (size < nsize)
409     {
410       GNUNET_break (0);
411       finish (handle, GNUNET_SYSERR);
412       return 0;
413     }
414   r = buf;
415   r->header.size = htons (nsize);
416   r->header.type = htons (GNUNET_MESSAGE_TYPE_STATISTICS_SET);
417   r->flags = 0;
418   r->value = GNUNET_htonll (handle->current->value);
419   if (handle->current->make_persistent)
420     r->flags |= htonl (GNUNET_STATISTICS_SETFLAG_PERSISTENT);
421   if (handle->current->type == ACTION_UPDATE)
422     r->flags |= htonl (GNUNET_STATISTICS_SETFLAG_RELATIVE);
423   GNUNET_assert (slen + nlen ==
424                  GNUNET_STRINGS_buffer_fill ((char *) &r[1],
425                                              slen + nlen,
426                                              2,
427                                              handle->current->subsystem,
428                                              handle->current->name));
429   finish (handle, GNUNET_OK);
430   return nsize;
431 }
432
433
434 static size_t
435 transmit_action (void *cls, size_t size, void *buf)
436 {
437   struct GNUNET_STATISTICS_Handle *handle = cls;
438   size_t ret;
439
440   handle->th = NULL;
441   switch (handle->current->type)
442     {
443     case ACTION_GET:
444       ret = transmit_get (handle, size, buf);
445       break;
446     case ACTION_SET:
447     case ACTION_UPDATE:
448       ret = transmit_set (handle, size, buf);
449       break;
450     default:
451       ret = 0;
452       GNUNET_break (0);
453       break; 
454     }
455   return ret;
456 }
457
458
459 /**
460  * Get handle for the statistics service.
461  *
462  * @param sched scheduler to use
463  * @param subsystem name of subsystem using the service
464  * @param cfg services configuration in use
465  * @return handle to use
466  */
467 struct GNUNET_STATISTICS_Handle *
468 GNUNET_STATISTICS_create (struct GNUNET_SCHEDULER_Handle *sched,
469                           const char *subsystem,
470                           const struct GNUNET_CONFIGURATION_Handle *cfg)
471 {
472   struct GNUNET_STATISTICS_Handle *ret;
473
474   GNUNET_assert (subsystem != NULL);
475   GNUNET_assert (sched != NULL);
476   GNUNET_assert (cfg != NULL);
477   ret = GNUNET_malloc (sizeof (struct GNUNET_STATISTICS_Handle));
478   ret->sched = sched;
479   ret->cfg = cfg;
480   ret->subsystem = GNUNET_strdup (subsystem);
481   try_connect (ret);
482   return ret;
483 }
484
485
486 /**
487  * Destroy a handle (free all state associated with
488  * it).
489  *
490  * @param h statistics handle to destroy
491  * @param sync_first set to GNUNET_YES if pending SET requests should
492  *        be completed
493  */
494 void
495 GNUNET_STATISTICS_destroy (struct GNUNET_STATISTICS_Handle *h,
496                            int sync_first)
497 {
498   struct ActionItem *pos;
499   struct ActionItem *next;
500   struct ActionItem *prev;
501   struct GNUNET_TIME_Relative timeout;
502
503   if (sync_first)
504     {
505       if (h->current != NULL)
506         {
507           if (h->current->type == ACTION_GET)
508             {
509               GNUNET_CLIENT_notify_transmit_ready_cancel (h->th);
510               h->th = NULL;
511             }
512         }
513       pos = h->action_head;
514       prev = NULL;
515       while (pos != NULL)
516         {
517           next = pos->next;
518           if (pos->type == ACTION_GET)
519             {
520               if (prev == NULL)
521                 h->action_head = next;
522               else
523                 prev->next = next;
524               free_action_item (pos);
525             }
526           else
527             {
528               prev = pos;
529             }
530           pos = next;
531         }
532       h->action_tail = prev;
533       if (h->current == NULL)
534         {
535           h->current = h->action_head;
536           if (h->action_head != NULL)
537             {
538               h->action_head = h->action_head->next;
539               if (h->action_head == NULL)
540                 h->action_tail = NULL;
541             }
542         }
543       if ( (h->current != NULL) &&
544            (h->th == NULL) )
545         {                                       
546           timeout = GNUNET_TIME_absolute_get_remaining (h->current->timeout);
547           h->th = GNUNET_CLIENT_notify_transmit_ready (h->client,
548                                                        h->current->msize,
549                                                        timeout,
550                                                        GNUNET_YES,
551                                                        &transmit_action, h);
552           GNUNET_assert (NULL != h->th);
553         }
554       h->do_destroy = GNUNET_YES;
555       return;
556     }
557   if (NULL != h->th)
558     {
559       GNUNET_CLIENT_notify_transmit_ready_cancel (h->th);
560       h->th = NULL;
561     }
562   if (h->current != NULL)
563     free_action_item (h->current);
564   while (NULL != (pos = h->action_head))
565     {
566       h->action_head = pos->next;
567       free_action_item (pos);
568     }
569   if (h->client != NULL)
570     {
571       GNUNET_CLIENT_disconnect (h->client);
572       h->client = NULL;
573     }
574   GNUNET_free (h->subsystem);
575   GNUNET_free (h);
576 }
577
578
579
580 /**
581  * Schedule the next action to be performed.
582  */
583 static void
584 schedule_action (struct GNUNET_STATISTICS_Handle *h)
585 {
586   struct GNUNET_TIME_Relative timeout;
587
588   if (h->current != NULL)
589     return;                     /* action already pending */
590   if (GNUNET_YES != try_connect (h))
591     {
592       finish (h, GNUNET_SYSERR);
593       return;
594     }
595
596   /* schedule next action */
597   h->current = h->action_head;
598   if (NULL == h->current)
599     {
600       if (h->do_destroy)
601         {
602           h->do_destroy = GNUNET_NO;
603           GNUNET_STATISTICS_destroy (h, GNUNET_YES);
604         }
605       return;
606     }
607   h->action_head = h->action_head->next;
608   if (NULL == h->action_head)
609     h->action_tail = NULL;
610   h->current->next = NULL;
611   timeout = GNUNET_TIME_absolute_get_remaining (h->current->timeout);
612   if (NULL ==
613       (h->th = GNUNET_CLIENT_notify_transmit_ready (h->client,
614                                                     h->current->msize,
615                                                     timeout,
616                                                     GNUNET_YES,
617                                                     &transmit_action, h)))
618     {
619 #if DEBUG_STATISTICS
620       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
621                   "Failed to transmit request to statistics service.\n");
622 #endif
623       finish (h, GNUNET_SYSERR);
624     }
625 }
626
627
628 static void
629 insert_ai (struct GNUNET_STATISTICS_Handle *h, struct ActionItem *ai)
630 {
631   if (h->action_tail == NULL)
632     {
633       h->action_head = ai;
634       h->action_tail = ai;
635       schedule_action (h);
636     }
637   else
638     {
639       h->action_tail->next = ai;
640       h->action_tail = ai;
641     }
642 }
643
644
645 /**
646  * Get statistic from the peer.
647  *
648  * @param handle identification of the statistics service
649  * @param subsystem limit to the specified subsystem, NULL for our subsystem
650  * @param name name of the statistic value, NULL for all values
651  * @param timeout after how long should we give up (and call
652  *        cont with an error code)?
653  * @param cont continuation to call when done (can be NULL)
654  * @param proc function to call on each value
655  * @param cls closure for cont and proc
656  */
657 void
658 GNUNET_STATISTICS_get (struct GNUNET_STATISTICS_Handle *handle,
659                        const char *subsystem,
660                        const char *name,
661                        struct GNUNET_TIME_Relative timeout,
662                        GNUNET_STATISTICS_Callback cont,
663                        GNUNET_STATISTICS_Iterator proc, void *cls)
664 {
665   size_t slen1;
666   size_t slen2;
667   struct ActionItem *ai;
668
669   GNUNET_assert (handle != NULL);
670   GNUNET_assert (proc != NULL);
671   GNUNET_assert (GNUNET_NO == handle->do_destroy);
672   if (GNUNET_YES != try_connect (handle))
673     {
674 #if DEBUG_STATISTICS
675       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
676                   "Failed to connect to statistics service, can not get value `%s:%s'.\n",
677                   strlen (subsystem) ? subsystem : "*",
678                   strlen (name) ? name : "*");
679 #endif
680       if (cont != NULL)
681         cont (cls, GNUNET_SYSERR);
682       return;
683     }
684   if (subsystem == NULL)
685     subsystem = "";
686   if (name == NULL)
687     name = "";
688   slen1 = strlen (subsystem);
689   slen2 = strlen (name);
690   GNUNET_assert (slen1 + slen2 + sizeof (struct GNUNET_MessageHeader) <
691                  GNUNET_SERVER_MAX_MESSAGE_SIZE);
692   ai = GNUNET_malloc (sizeof (struct ActionItem));
693   ai->subsystem = GNUNET_strdup (subsystem);
694   ai->name = GNUNET_strdup (name);
695   ai->cont = cont;
696   ai->proc = proc;
697   ai->cls = cls;
698   ai->timeout = GNUNET_TIME_relative_to_absolute (timeout);
699   ai->type = ACTION_GET;
700   ai->msize = slen1 + slen2 + sizeof (struct GNUNET_MessageHeader);
701   insert_ai (handle, ai);
702 }
703
704
705 static void
706 add_setter_action (struct GNUNET_STATISTICS_Handle *h,
707                    const char *name,
708                    int make_persistent,
709                    uint64_t value, enum ActionType type)
710 {
711   struct ActionItem *ai;
712   size_t slen;
713   size_t nlen;
714   size_t nsize;
715
716   GNUNET_assert (h != NULL);
717   GNUNET_assert (name != NULL);
718   if (GNUNET_YES != try_connect (h))
719     return;
720   slen = strlen (h->subsystem) + 1;
721   nlen = strlen (name) + 1;
722   nsize = sizeof (struct GNUNET_STATISTICS_SetMessage) + slen + nlen;
723   if (nsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
724     {
725       GNUNET_break (0);
726       return;
727     }
728   ai = GNUNET_malloc (sizeof (struct ActionItem));
729   ai->subsystem = GNUNET_strdup (h->subsystem);
730   ai->name = GNUNET_strdup (name);
731   ai->timeout = GNUNET_TIME_relative_to_absolute (SET_TRANSMIT_TIMEOUT);
732   ai->make_persistent = make_persistent;
733   ai->msize = nsize;
734   ai->value = value;
735   ai->type = type;
736   insert_ai (h, ai);
737   schedule_action (h);
738 }
739
740
741 /**
742  * Set statistic value for the peer.  Will always use our
743  * subsystem (the argument used when "handle" was created).
744  *
745  * @param handle identification of the statistics service
746  * @param name name of the statistic value
747  * @param value new value to set
748  * @param make_persistent should the value be kept across restarts?
749  */
750 void
751 GNUNET_STATISTICS_set (struct GNUNET_STATISTICS_Handle *handle,
752                        const char *name,
753                        uint64_t value, int make_persistent)
754 {
755   GNUNET_assert (GNUNET_NO == handle->do_destroy);
756   add_setter_action (handle, name, make_persistent, value, ACTION_SET);
757 }
758
759
760 /**
761  * Set statistic value for the peer.  Will always use our
762  * subsystem (the argument used when "handle" was created).
763  *
764  * @param handle identification of the statistics service
765  * @param name name of the statistic value
766  * @param delta change in value (added to existing value)
767  * @param make_persistent should the value be kept across restarts?
768  */
769 void
770 GNUNET_STATISTICS_update (struct GNUNET_STATISTICS_Handle *handle,
771                           const char *name,
772                           int64_t delta, int make_persistent)
773 {
774   GNUNET_assert (GNUNET_NO == handle->do_destroy);
775   add_setter_action (handle, name, make_persistent,
776                      (unsigned long long) delta, ACTION_UPDATE);
777 }
778
779
780 /* end of statistics_api.c */