-doxygen, indentation
[oweals/gnunet.git] / src / statistics / statistics_api.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009, 2010, 2011 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 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 statistics/statistics_api.c
23  * @brief API of the statistics service
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet_util_lib.h"
28 #include "gnunet_constants.h"
29 #include "gnunet_protocols.h"
30 #include "gnunet_statistics_service.h"
31 #include "statistics.h"
32
33 /**
34  * How long do we wait until a statistics request for setting
35  * a value times out?  (The update will be lost if the
36  * service does not react within this timeframe).
37  */
38 #define SET_TRANSMIT_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 2)
39
40 #define LOG(kind,...) GNUNET_log_from (kind, "statistics-api",__VA_ARGS__)
41
42 /**
43  * Types of actions.
44  */
45 enum ActionType
46 {
47   /**
48    * Get a value.
49    */
50   ACTION_GET,
51
52   /**
53    * Set a value.
54    */
55   ACTION_SET,
56
57   /**
58    * Update a value.
59    */
60   ACTION_UPDATE,
61
62   /**
63    * Watch a value.
64    */
65   ACTION_WATCH
66 };
67
68
69 /**
70  * Entry kept for each value we are watching.
71  */
72 struct GNUNET_STATISTICS_WatchEntry
73 {
74
75   /**
76    * What subsystem is this action about? (never NULL)
77    */
78   char *subsystem;
79
80   /**
81    * What value is this action about? (never NULL)
82    */
83   char *name;
84
85   /**
86    * Function to call
87    */
88   GNUNET_STATISTICS_Iterator proc;
89
90   /**
91    * Closure for proc
92    */
93   void *proc_cls;
94
95 };
96
97
98 /**
99  * Linked list of things we still need to do.
100  */
101 struct GNUNET_STATISTICS_GetHandle
102 {
103
104   /**
105    * This is a doubly linked list.
106    */
107   struct GNUNET_STATISTICS_GetHandle *next;
108
109   /**
110    * This is a doubly linked list.
111    */
112   struct GNUNET_STATISTICS_GetHandle *prev;
113
114   /**
115    * Main statistics handle.
116    */
117   struct GNUNET_STATISTICS_Handle *sh;
118
119   /**
120    * What subsystem is this action about? (can be NULL)
121    */
122   char *subsystem;
123
124   /**
125    * What value is this action about? (can be NULL)
126    */
127   char *name;
128
129   /**
130    * Continuation to call once action is complete.
131    */
132   GNUNET_STATISTICS_Callback cont;
133
134   /**
135    * Function to call (for GET actions only).
136    */
137   GNUNET_STATISTICS_Iterator proc;
138
139   /**
140    * Closure for proc and cont.
141    */
142   void *cls;
143
144   /**
145    * Timeout for this action.
146    */
147   struct GNUNET_TIME_Absolute timeout;
148
149   /**
150    * Associated value.
151    */
152   uint64_t value;
153
154   /**
155    * Flag for SET/UPDATE actions.
156    */
157   int make_persistent;
158
159   /**
160    * Has the current iteration been aborted; for GET actions.
161    */
162   int aborted;
163
164   /**
165    * Is this a GET, SET, UPDATE or WATCH?
166    */
167   enum ActionType type;
168
169   /**
170    * Size of the message that we will be transmitting.
171    */
172   uint16_t msize;
173
174 };
175
176
177 /**
178  * Handle for the service.
179  */
180 struct GNUNET_STATISTICS_Handle
181 {
182   /**
183    * Name of our subsystem.
184    */
185   char *subsystem;
186
187   /**
188    * Configuration to use.
189    */
190   const struct GNUNET_CONFIGURATION_Handle *cfg;
191
192   /**
193    * Socket (if available).
194    */
195   struct GNUNET_CLIENT_Connection *client;
196
197   /**
198    * Currently pending transmission request.
199    */
200   struct GNUNET_CLIENT_TransmitHandle *th;
201
202   /**
203    * Head of the linked list of pending actions (first action
204    * to be performed).
205    */
206   struct GNUNET_STATISTICS_GetHandle *action_head;
207
208   /**
209    * Tail of the linked list of actions (for fast append).
210    */
211   struct GNUNET_STATISTICS_GetHandle *action_tail;
212
213   /**
214    * Action we are currently busy with (action request has been
215    * transmitted, we're now receiving the response from the
216    * service).
217    */
218   struct GNUNET_STATISTICS_GetHandle *current;
219
220   /**
221    * Array of watch entries.
222    */
223   struct GNUNET_STATISTICS_WatchEntry **watches;
224
225   /**
226    * Task doing exponential back-off trying to reconnect.
227    */
228   GNUNET_SCHEDULER_TaskIdentifier backoff_task;
229
230   /**
231    * Time for next connect retry.
232    */
233   struct GNUNET_TIME_Relative backoff;
234
235   /**
236    * Maximum heap size observed so far (if available).
237    */
238   uint64_t peak_heap_size;
239
240   /**
241    * Maximum resident set side observed so far (if available).
242    */
243   uint64_t peak_rss;
244
245   /**
246    * Size of the 'watches' array.
247    */
248   unsigned int watches_size;
249
250   /**
251    * Should this handle auto-destruct once all actions have
252    * been processed?
253    */
254   int do_destroy;
255
256   /**
257    * Are we currently receiving from the service?
258    */
259   int receiving;
260
261 };
262
263
264 /**
265  * Obtain statistics about this process's memory consumption and
266  * report those as well (if they changed).
267  */
268 static void
269 update_memory_statistics (struct GNUNET_STATISTICS_Handle *h)
270 {
271 #if ENABLE_HEAP_STATISTICS
272   uint64_t current_heap_size = 0;
273   uint64_t current_rss = 0;
274
275   if (GNUNET_NO != h->do_destroy)
276     return;
277 #if HAVE_MALLINFO
278   {
279     struct mallinfo mi;
280
281     mi = mallinfo();
282     current_heap_size = mi.uordblks + mi.fordblks;
283   }
284 #endif
285 #if HAVE_GETRUSAGE
286   {
287     struct rusage ru;
288
289     if (0 == getrusage (RUSAGE_SELF, &ru))
290     {
291       current_rss = 1024LL * ru.ru_maxrss;
292     }
293   }
294 #endif
295   if (current_heap_size > h->peak_heap_size)
296   {
297     h->peak_heap_size = current_heap_size;
298     GNUNET_STATISTICS_set (h, "# peak heap size", current_heap_size, GNUNET_NO);
299   }
300   if (current_rss > h->peak_rss)
301   {
302     h->peak_rss = current_rss;
303     GNUNET_STATISTICS_set (h, "# peak resident set size", current_rss, GNUNET_NO);
304   }
305 #endif
306 }
307
308
309 /**
310  * Schedule the next action to be performed.
311  *
312  * @param h statistics handle to reconnect
313  */
314 static void
315 schedule_action (struct GNUNET_STATISTICS_Handle *h);
316
317
318 /**
319  * Transmit request to service that we want to watch
320  * the development of a particular value.
321  *
322  * @param h statistics handle
323  * @param watch watch entry of the value to watch
324  */
325 static void
326 schedule_watch_request (struct GNUNET_STATISTICS_Handle *h,
327                         struct GNUNET_STATISTICS_WatchEntry *watch)
328 {
329   struct GNUNET_STATISTICS_GetHandle *ai;
330   size_t slen;
331   size_t nlen;
332   size_t nsize;
333
334   slen = strlen (watch->subsystem) + 1;
335   nlen = strlen (watch->name) + 1;
336   nsize = sizeof (struct GNUNET_MessageHeader) + slen + nlen;
337   if (nsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
338   {
339     GNUNET_break (0);
340     return;
341   }
342   ai = GNUNET_new (struct GNUNET_STATISTICS_GetHandle);
343   ai->sh = h;
344   ai->subsystem = GNUNET_strdup (watch->subsystem);
345   ai->name = GNUNET_strdup (watch->name);
346   ai->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
347   ai->msize = nsize;
348   ai->type = ACTION_WATCH;
349   ai->proc = watch->proc;
350   ai->cls = watch->proc_cls;
351   GNUNET_CONTAINER_DLL_insert_tail (h->action_head, h->action_tail,
352                                     ai);
353   schedule_action (h);
354 }
355
356
357 /**
358  * Free memory associated with the given action item.
359  *
360  * @param gh action item to free
361  */
362 static void
363 free_action_item (struct GNUNET_STATISTICS_GetHandle *gh)
364 {
365   GNUNET_free_non_null (gh->subsystem);
366   GNUNET_free_non_null (gh->name);
367   GNUNET_free (gh);
368 }
369
370
371 /**
372  * Disconnect from the statistics service.
373  *
374  * @param h statistics handle to disconnect from
375  */
376 static void
377 do_disconnect (struct GNUNET_STATISTICS_Handle *h)
378 {
379   struct GNUNET_STATISTICS_GetHandle *c;
380
381   if (NULL != h->th)
382   {
383     GNUNET_CLIENT_notify_transmit_ready_cancel (h->th);
384     h->th = NULL;
385   }
386   h->receiving = GNUNET_NO;
387   if (NULL != (c = h->current))
388   {
389     h->current = NULL;
390     if ( (NULL != c->cont) &&
391          (GNUNET_YES != c->aborted) )
392       c->cont (c->cls, GNUNET_SYSERR);
393     free_action_item (c);
394   }
395   if (NULL != h->client)
396   {
397     GNUNET_CLIENT_disconnect (h->client);
398     h->client = NULL;
399   }
400 }
401
402
403 /**
404  * Try to (re)connect to the statistics service.
405  *
406  * @param h statistics handle to reconnect
407  * @return #GNUNET_YES on success, #GNUNET_NO on failure.
408  */
409 static int
410 try_connect (struct GNUNET_STATISTICS_Handle *h)
411 {
412   struct GNUNET_STATISTICS_GetHandle *gh;
413   struct GNUNET_STATISTICS_GetHandle *gn;
414   unsigned int i;
415
416   if (GNUNET_SCHEDULER_NO_TASK != h->backoff_task)
417     return GNUNET_NO;
418   if (NULL != h->client)
419     return GNUNET_YES;
420   h->client = GNUNET_CLIENT_connect ("statistics", h->cfg);
421   if (NULL != h->client)
422   {
423     gn = h->action_head;
424     while (NULL != (gh = gn))
425     {
426       gn = gh->next;
427       if (gh->type == ACTION_WATCH)
428       {
429         GNUNET_CONTAINER_DLL_remove (h->action_head,
430                                      h->action_tail,
431                                      gh);
432         free_action_item (gh);
433       }
434     }
435     for (i = 0; i < h->watches_size; i++)
436     {
437       if (NULL != h->watches[i])
438         schedule_watch_request (h, h->watches[i]);
439     }
440     return GNUNET_YES;
441   }
442   LOG (GNUNET_ERROR_TYPE_DEBUG,
443        "Failed to connect to statistics service!\n");
444   return GNUNET_NO;
445 }
446
447
448 /**
449  * We've waited long enough, reconnect now.
450  *
451  * @param cls the `struct GNUNET_STATISTICS_Handle` to reconnect
452  * @param tc scheduler context (unused)
453  */
454 static void
455 reconnect_task (void *cls,
456                 const struct GNUNET_SCHEDULER_TaskContext *tc)
457 {
458   struct GNUNET_STATISTICS_Handle *h = cls;
459
460   h->backoff_task = GNUNET_SCHEDULER_NO_TASK;
461   schedule_action (h);
462 }
463
464
465 /**
466  * Task used by 'reconnect_later' to shutdown the handle
467  *
468  * @param cls the statistics handle
469  * @param tc scheduler context
470  */
471 static void
472 do_destroy (void *cls,
473             const struct GNUNET_SCHEDULER_TaskContext *tc)
474 {
475   struct GNUNET_STATISTICS_Handle *h = cls;
476
477   GNUNET_STATISTICS_destroy (h, GNUNET_NO);
478 }
479
480
481 /**
482  * Reconnect at a later time, respecting back-off.
483  *
484  * @param h statistics handle
485  */
486 static void
487 reconnect_later (struct GNUNET_STATISTICS_Handle *h)
488 {
489   int loss;
490   struct GNUNET_STATISTICS_GetHandle *gh;
491
492   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == h->backoff_task);
493   if (GNUNET_YES == h->do_destroy)
494   {
495     /* So we are shutting down and the service is not reachable.
496      * Chances are that it's down for good and we are not going to connect to
497      * it anymore.
498      * Give up and don't sync the rest of the data.
499      */
500     loss = GNUNET_NO;
501     for (gh = h->action_head; NULL != gh; gh = gh->next)
502       if ( (gh->make_persistent) && (ACTION_SET == gh->type) )
503         loss = GNUNET_YES;
504     if (GNUNET_YES == loss)
505       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
506                   _("Could not save some persistent statistics\n"));
507     h->do_destroy = GNUNET_NO;
508     GNUNET_SCHEDULER_add_continuation (&do_destroy, h,
509                                        GNUNET_SCHEDULER_REASON_PREREQ_DONE);
510     return;
511   }
512   h->backoff_task =
513     GNUNET_SCHEDULER_add_delayed (h->backoff, &reconnect_task, h);
514   h->backoff = GNUNET_TIME_STD_BACKOFF (h->backoff);
515 }
516
517
518 /**
519  * Process a #GNUNET_MESSAGE_TYPE_STATISTICS_VALUE message.
520  *
521  * @param h statistics handle
522  * @param msg message received from the service, never NULL
523  * @return #GNUNET_OK if the message was well-formed
524  */
525 static int
526 process_statistics_value_message (struct GNUNET_STATISTICS_Handle *h,
527                                   const struct GNUNET_MessageHeader *msg)
528 {
529   char *service;
530   char *name;
531   const struct GNUNET_STATISTICS_ReplyMessage *smsg;
532   uint16_t size;
533
534   if (h->current->aborted)
535   {
536     LOG (GNUNET_ERROR_TYPE_DEBUG,
537          "Iteration was aborted, ignoring VALUE\n");
538     return GNUNET_OK;           /* don't bother */
539   }
540   size = ntohs (msg->size);
541   if (size < sizeof (struct GNUNET_STATISTICS_ReplyMessage))
542   {
543     GNUNET_break (0);
544     return GNUNET_SYSERR;
545   }
546   smsg = (const struct GNUNET_STATISTICS_ReplyMessage *) msg;
547   size -= sizeof (struct GNUNET_STATISTICS_ReplyMessage);
548   if (size !=
549       GNUNET_STRINGS_buffer_tokenize ((const char *) &smsg[1], size, 2,
550                                       &service, &name))
551   {
552     GNUNET_break (0);
553     return GNUNET_SYSERR;
554   }
555   LOG (GNUNET_ERROR_TYPE_DEBUG,
556        "Received valid statistic on `%s:%s': %llu\n",
557        service, name,
558        GNUNET_ntohll (smsg->value));
559   if (GNUNET_OK !=
560       h->current->proc (h->current->cls, service, name,
561                         GNUNET_ntohll (smsg->value),
562                         0 !=
563                         (ntohl (smsg->uid) & GNUNET_STATISTICS_PERSIST_BIT)))
564   {
565     LOG (GNUNET_ERROR_TYPE_DEBUG,
566          "Processing of remaining statistics aborted by client.\n");
567     h->current->aborted = GNUNET_YES;
568   }
569   LOG (GNUNET_ERROR_TYPE_DEBUG,
570        "VALUE processed successfully\n");
571   return GNUNET_OK;
572 }
573
574
575 /**
576  * We have received a watch value from the service.  Process it.
577  *
578  * @param h statistics handle
579  * @param msg the watch value message
580  * @return #GNUNET_OK if the message was well-formed, #GNUNET_SYSERR if not,
581  *         #GNUNET_NO if this watch has been cancelled
582  */
583 static int
584 process_watch_value (struct GNUNET_STATISTICS_Handle *h,
585                      const struct GNUNET_MessageHeader *msg)
586 {
587   const struct GNUNET_STATISTICS_WatchValueMessage *wvm;
588   struct GNUNET_STATISTICS_WatchEntry *w;
589   uint32_t wid;
590
591   if (sizeof (struct GNUNET_STATISTICS_WatchValueMessage) != ntohs (msg->size))
592   {
593     GNUNET_break (0);
594     return GNUNET_SYSERR;
595   }
596   wvm = (const struct GNUNET_STATISTICS_WatchValueMessage *) msg;
597   GNUNET_break (0 == ntohl (wvm->reserved));
598   wid = ntohl (wvm->wid);
599   if (wid >= h->watches_size)
600   {
601     GNUNET_break (0);
602     return GNUNET_SYSERR;
603   }
604   w = h->watches[wid];
605   if (NULL == w)
606     return GNUNET_NO;
607   (void) w->proc (w->proc_cls, w->subsystem, w->name,
608                   GNUNET_ntohll (wvm->value),
609                   0 != (ntohl (wvm->flags) & GNUNET_STATISTICS_PERSIST_BIT));
610   return GNUNET_OK;
611 }
612
613
614 /**
615  * Task used to destroy the statistics handle.
616  *
617  * @param cls the `struct GNUNET_STATISTICS_Handle`
618  * @param tc the scheduler context
619  */
620 static void
621 destroy_task (void *cls,
622               const struct GNUNET_SCHEDULER_TaskContext *tc)
623 {
624   struct GNUNET_STATISTICS_Handle *h = cls;
625
626   GNUNET_STATISTICS_destroy (h, GNUNET_NO);
627 }
628
629
630 /**
631  * Function called with messages from stats service.
632  *
633  * @param cls closure
634  * @param msg message received, NULL on timeout or fatal error
635  */
636 static void
637 receive_stats (void *cls,
638                const struct GNUNET_MessageHeader *msg)
639 {
640   struct GNUNET_STATISTICS_Handle *h = cls;
641   struct GNUNET_STATISTICS_GetHandle *c;
642   int ret;
643
644   if (NULL == msg)
645   {
646     LOG (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
647          "Error receiving statistics from service, is the service running?\n");
648     do_disconnect (h);
649     reconnect_later (h);
650     return;
651   }
652   switch (ntohs (msg->type))
653   {
654   case GNUNET_MESSAGE_TYPE_TEST:
655     if (GNUNET_SYSERR != h->do_destroy)
656     {
657       /* not in shutdown, why do we get 'TEST'? */
658       GNUNET_break (0);
659       do_disconnect (h);
660       reconnect_later (h);
661       return;
662     }
663     h->do_destroy = GNUNET_NO;
664     GNUNET_SCHEDULER_add_continuation (&destroy_task, h,
665                                        GNUNET_SCHEDULER_REASON_PREREQ_DONE);
666     break;
667   case GNUNET_MESSAGE_TYPE_STATISTICS_END:
668     LOG (GNUNET_ERROR_TYPE_DEBUG,
669          "Received end of statistics marker\n");
670     if (NULL == (c = h->current))
671     {
672       GNUNET_break (0);
673       do_disconnect (h);
674       reconnect_later (h);
675       return;
676     }
677     h->backoff = GNUNET_TIME_UNIT_MILLISECONDS;
678     if (h->watches_size > 0)
679     {
680       GNUNET_CLIENT_receive (h->client, &receive_stats, h,
681                              GNUNET_TIME_UNIT_FOREVER_REL);
682     }
683     else
684     {
685       h->receiving = GNUNET_NO;
686     }
687     h->current = NULL;
688     schedule_action (h);
689     if (NULL != c->cont)
690       c->cont (c->cls, GNUNET_OK);
691     free_action_item (c);
692     return;
693   case GNUNET_MESSAGE_TYPE_STATISTICS_VALUE:
694     if (GNUNET_OK != process_statistics_value_message (h, msg))
695     {
696       do_disconnect (h);
697       reconnect_later (h);
698       return;
699     }
700     /* finally, look for more! */
701     LOG (GNUNET_ERROR_TYPE_DEBUG,
702          "Processing VALUE done, now reading more\n");
703     GNUNET_CLIENT_receive (h->client, &receive_stats, h,
704                            GNUNET_TIME_absolute_get_remaining (h->
705                                                                current->timeout));
706     h->backoff = GNUNET_TIME_UNIT_MILLISECONDS;
707     return;
708   case GNUNET_MESSAGE_TYPE_STATISTICS_WATCH_VALUE:
709     if (GNUNET_OK !=
710         (ret = process_watch_value (h, msg)))
711     {
712       do_disconnect (h);
713       if (GNUNET_NO == ret)
714         h->backoff = GNUNET_TIME_UNIT_MILLISECONDS;
715       reconnect_later (h);
716       return;
717     }
718     h->backoff = GNUNET_TIME_UNIT_MILLISECONDS;
719     GNUNET_assert (h->watches_size > 0);
720     GNUNET_CLIENT_receive (h->client, &receive_stats, h,
721                            GNUNET_TIME_UNIT_FOREVER_REL);
722     return;
723   default:
724     GNUNET_break (0);
725     do_disconnect (h);
726     reconnect_later (h);
727     return;
728   }
729 }
730
731
732 /**
733  * Transmit a GET request (and if successful, start to receive
734  * the response).
735  *
736  * @param handle statistics handle
737  * @param size how many bytes can we write to @a buf
738  * @param buf where to write requests to the service
739  * @return number of bytes written to @a buf
740  */
741 static size_t
742 transmit_get (struct GNUNET_STATISTICS_Handle *handle,
743               size_t size,
744               void *buf)
745 {
746   struct GNUNET_STATISTICS_GetHandle *c;
747   struct GNUNET_MessageHeader *hdr;
748   size_t slen1;
749   size_t slen2;
750   uint16_t msize;
751
752   GNUNET_assert (NULL != (c = handle->current));
753   if (NULL == buf)
754   {
755     /* timeout / error */
756     LOG (GNUNET_ERROR_TYPE_DEBUG,
757          "Transmission of request for statistics failed!\n");
758     do_disconnect (handle);
759     reconnect_later (handle);
760     return 0;
761   }
762   slen1 = strlen (c->subsystem) + 1;
763   slen2 = strlen (c->name) + 1;
764   msize = slen1 + slen2 + sizeof (struct GNUNET_MessageHeader);
765   GNUNET_assert (msize <= size);
766   hdr = (struct GNUNET_MessageHeader *) buf;
767   hdr->size = htons (msize);
768   hdr->type = htons (GNUNET_MESSAGE_TYPE_STATISTICS_GET);
769   GNUNET_assert (slen1 + slen2 ==
770                  GNUNET_STRINGS_buffer_fill ((char *) &hdr[1], slen1 + slen2, 2,
771                                              c->subsystem,
772                                              c->name));
773   if (GNUNET_YES != handle->receiving)
774   {
775     LOG (GNUNET_ERROR_TYPE_DEBUG,
776          "Transmission of GET done, now reading response\n");
777     handle->receiving = GNUNET_YES;
778     GNUNET_CLIENT_receive (handle->client, &receive_stats, handle,
779                            GNUNET_TIME_absolute_get_remaining (c->timeout));
780   }
781   return msize;
782 }
783
784
785 /**
786  * Transmit a WATCH request (and if successful, start to receive
787  * the response).
788  *
789  * @param handle statistics handle
790  * @param size how many bytes can we write to @a buf
791  * @param buf where to write requests to the service
792  * @return number of bytes written to @a buf
793  */
794 static size_t
795 transmit_watch (struct GNUNET_STATISTICS_Handle *handle,
796                 size_t size,
797                 void *buf)
798 {
799   struct GNUNET_MessageHeader *hdr;
800   size_t slen1;
801   size_t slen2;
802   uint16_t msize;
803
804   if (NULL == buf)
805   {
806     /* timeout / error */
807     LOG (GNUNET_ERROR_TYPE_DEBUG,
808          "Transmission of request for statistics failed!\n");
809     do_disconnect (handle);
810     reconnect_later (handle);
811     return 0;
812   }
813   LOG (GNUNET_ERROR_TYPE_DEBUG,
814        "Transmitting watch request for `%s'\n",
815        handle->current->name);
816   slen1 = strlen (handle->current->subsystem) + 1;
817   slen2 = strlen (handle->current->name) + 1;
818   msize = slen1 + slen2 + sizeof (struct GNUNET_MessageHeader);
819   GNUNET_assert (msize <= size);
820   hdr = (struct GNUNET_MessageHeader *) buf;
821   hdr->size = htons (msize);
822   hdr->type = htons (GNUNET_MESSAGE_TYPE_STATISTICS_WATCH);
823   GNUNET_assert (slen1 + slen2 ==
824                  GNUNET_STRINGS_buffer_fill ((char *) &hdr[1], slen1 + slen2, 2,
825                                              handle->current->subsystem,
826                                              handle->current->name));
827   if (GNUNET_YES != handle->receiving)
828   {
829     handle->receiving = GNUNET_YES;
830     GNUNET_CLIENT_receive (handle->client, &receive_stats, handle,
831                            GNUNET_TIME_UNIT_FOREVER_REL);
832   }
833   GNUNET_assert (NULL == handle->current->cont);
834   free_action_item (handle->current);
835   handle->current = NULL;
836   return msize;
837 }
838
839
840 /**
841  * Transmit a SET/UPDATE request.
842  *
843  * @param handle statistics handle
844  * @param size how many bytes can we write to @a buf
845  * @param buf where to write requests to the service
846  * @return number of bytes written to @a buf
847  */
848 static size_t
849 transmit_set (struct GNUNET_STATISTICS_Handle *handle,
850               size_t size,
851               void *buf)
852 {
853   struct GNUNET_STATISTICS_SetMessage *r;
854   size_t slen;
855   size_t nlen;
856   size_t nsize;
857
858   if (NULL == buf)
859   {
860     do_disconnect (handle);
861     reconnect_later (handle);
862     return 0;
863   }
864   slen = strlen (handle->current->subsystem) + 1;
865   nlen = strlen (handle->current->name) + 1;
866   nsize = sizeof (struct GNUNET_STATISTICS_SetMessage) + slen + nlen;
867   if (size < nsize)
868   {
869     GNUNET_break (0);
870     do_disconnect (handle);
871     reconnect_later (handle);
872     return 0;
873   }
874   r = buf;
875   r->header.size = htons (nsize);
876   r->header.type = htons (GNUNET_MESSAGE_TYPE_STATISTICS_SET);
877   r->flags = 0;
878   r->value = GNUNET_htonll (handle->current->value);
879   if (handle->current->make_persistent)
880     r->flags |= htonl (GNUNET_STATISTICS_SETFLAG_PERSISTENT);
881   if (handle->current->type == ACTION_UPDATE)
882     r->flags |= htonl (GNUNET_STATISTICS_SETFLAG_RELATIVE);
883   GNUNET_assert (slen + nlen ==
884                  GNUNET_STRINGS_buffer_fill ((char *) &r[1], slen + nlen, 2,
885                                              handle->current->subsystem,
886                                              handle->current->name));
887   GNUNET_assert (NULL == handle->current->cont);
888   free_action_item (handle->current);
889   handle->current = NULL;
890   update_memory_statistics (handle);
891   return nsize;
892 }
893
894
895 /**
896  * Function called when we are ready to transmit a request to the service.
897  *
898  * @param cls the `struct GNUNET_STATISTICS_Handle`
899  * @param size how many bytes can we write to @a buf
900  * @param buf where to write requests to the service
901  * @return number of bytes written to @a buf
902  */
903 static size_t
904 transmit_action (void *cls, size_t size, void *buf)
905 {
906   struct GNUNET_STATISTICS_Handle *h = cls;
907   size_t ret;
908
909   h->th = NULL;
910   ret = 0;
911   if (NULL != h->current)
912     switch (h->current->type)
913     {
914     case ACTION_GET:
915       ret = transmit_get (h, size, buf);
916       break;
917     case ACTION_SET:
918     case ACTION_UPDATE:
919       ret = transmit_set (h, size, buf);
920       break;
921     case ACTION_WATCH:
922       ret = transmit_watch (h, size, buf);
923       break;
924     default:
925       GNUNET_assert (0);
926       break;
927     }
928   schedule_action (h);
929   return ret;
930 }
931
932
933 /**
934  * Get handle for the statistics service.
935  *
936  * @param subsystem name of subsystem using the service
937  * @param cfg services configuration in use
938  * @return handle to use
939  */
940 struct GNUNET_STATISTICS_Handle *
941 GNUNET_STATISTICS_create (const char *subsystem,
942                           const struct GNUNET_CONFIGURATION_Handle *cfg)
943 {
944   struct GNUNET_STATISTICS_Handle *ret;
945
946   if (GNUNET_YES ==
947       GNUNET_CONFIGURATION_get_value_yesno (cfg, "statistics", "DISABLE"))
948     return NULL;
949   GNUNET_assert (NULL != subsystem);
950   GNUNET_assert (NULL != cfg);
951   ret = GNUNET_new (struct GNUNET_STATISTICS_Handle);
952   ret->cfg = cfg;
953   ret->subsystem = GNUNET_strdup (subsystem);
954   ret->backoff = GNUNET_TIME_UNIT_MILLISECONDS;
955   return ret;
956 }
957
958
959 /**
960  * Destroy a handle (free all state associated with
961  * it).
962  *
963  * @param h statistics handle to destroy
964  * @param sync_first set to #GNUNET_YES if pending SET requests should
965  *        be completed
966  */
967 void
968 GNUNET_STATISTICS_destroy (struct GNUNET_STATISTICS_Handle *h,
969                            int sync_first)
970 {
971   struct GNUNET_STATISTICS_GetHandle *pos;
972   struct GNUNET_STATISTICS_GetHandle *next;
973   struct GNUNET_TIME_Relative timeout;
974   int i;
975
976   if (NULL == h)
977     return;
978   GNUNET_assert (GNUNET_NO == h->do_destroy); // Don't call twice.
979   if (GNUNET_SCHEDULER_NO_TASK != h->backoff_task)
980   {
981     GNUNET_SCHEDULER_cancel (h->backoff_task);
982     h->backoff_task = GNUNET_SCHEDULER_NO_TASK;
983   }
984   if (sync_first)
985   {
986     if (NULL != h->current)
987     {
988       if (ACTION_GET == h->current->type)
989       {
990         if (NULL != h->th)
991         {
992           GNUNET_CLIENT_notify_transmit_ready_cancel (h->th);
993           h->th = NULL;
994         }
995         free_action_item (h->current);
996         h->current = NULL;
997       }
998     }
999     next = h->action_head;
1000     while (NULL != (pos = next))
1001     {
1002       next = pos->next;
1003       if (ACTION_GET == pos->type)
1004       {
1005         GNUNET_CONTAINER_DLL_remove (h->action_head,
1006                                      h->action_tail,
1007                                      pos);
1008         free_action_item (pos);
1009       }
1010     }
1011     if ( (NULL == h->current) &&
1012          (NULL != (h->current = h->action_head)) )
1013       GNUNET_CONTAINER_DLL_remove (h->action_head,
1014                                    h->action_tail,
1015                                    h->current);
1016     h->do_destroy = GNUNET_YES;
1017     if ((NULL != h->current) && (NULL == h->th) &&
1018         (NULL != h->client))
1019     {
1020       timeout = GNUNET_TIME_absolute_get_remaining (h->current->timeout);
1021       h->th =
1022         GNUNET_CLIENT_notify_transmit_ready (h->client, h->current->msize,
1023                                              timeout, GNUNET_YES,
1024                                              &transmit_action, h);
1025       GNUNET_assert (NULL != h->th);
1026     }
1027     if (NULL != h->th)
1028       return; /* do not finish destruction just yet */
1029   }
1030   while (NULL != (pos = h->action_head))
1031   {
1032     GNUNET_CONTAINER_DLL_remove (h->action_head,
1033                                  h->action_tail,
1034                                  pos);
1035     free_action_item (pos);
1036   }
1037   do_disconnect (h);
1038   for (i = 0; i < h->watches_size; i++)
1039   {
1040     if (NULL == h->watches[i])
1041       continue;
1042     GNUNET_free (h->watches[i]->subsystem);
1043     GNUNET_free (h->watches[i]->name);
1044     GNUNET_free (h->watches[i]);
1045   }
1046   GNUNET_array_grow (h->watches, h->watches_size, 0);
1047   GNUNET_free (h->subsystem);
1048   GNUNET_free (h);
1049 }
1050
1051
1052 /**
1053  * Function called to transmit TEST message to service to
1054  * confirm that the service has received all of our 'SET'
1055  * messages (during statistics disconnect/shutdown).
1056  *
1057  * @param cls the `struct GNUNET_STATISTICS_Handle`
1058  * @param size how many bytes can we write to @a buf
1059  * @param buf where to write requests to the service
1060  * @return number of bytes written to @a buf
1061  */
1062 static size_t
1063 transmit_test_on_shutdown (void *cls,
1064                            size_t size,
1065                            void *buf)
1066 {
1067   struct GNUNET_STATISTICS_Handle *h = cls;
1068   struct GNUNET_MessageHeader hdr;
1069
1070   h->th = NULL;
1071   if (NULL == buf)
1072   {
1073     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1074                 _("Failed to receive acknowledgement from statistics service, some statistics might have been lost!\n"));
1075     h->do_destroy = GNUNET_NO;
1076     GNUNET_SCHEDULER_add_continuation (&destroy_task, h,
1077                                        GNUNET_SCHEDULER_REASON_PREREQ_DONE);
1078     return 0;
1079   }
1080   hdr.type = htons (GNUNET_MESSAGE_TYPE_TEST);
1081   hdr.size = htons (sizeof (struct GNUNET_MessageHeader));
1082   memcpy (buf, &hdr, sizeof (hdr));
1083   if (GNUNET_YES != h->receiving)
1084   {
1085     h->receiving = GNUNET_YES;
1086     GNUNET_CLIENT_receive (h->client, &receive_stats, h,
1087                            GNUNET_TIME_UNIT_FOREVER_REL);
1088   }
1089   return sizeof (struct GNUNET_MessageHeader);
1090 }
1091
1092
1093 /**
1094  * Schedule the next action to be performed.
1095  *
1096  * @param h statistics handle
1097  */
1098 static void
1099 schedule_action (struct GNUNET_STATISTICS_Handle *h)
1100 {
1101   struct GNUNET_TIME_Relative timeout;
1102
1103   if ( (NULL != h->th) ||
1104        (GNUNET_SCHEDULER_NO_TASK != h->backoff_task) )
1105     return;                     /* action already pending */
1106   if (GNUNET_YES != try_connect (h))
1107   {
1108     reconnect_later (h);
1109     return;
1110   }
1111   if (NULL != h->current)
1112     return; /* action already pending */
1113   /* schedule next action */
1114   h->current = h->action_head;
1115   if (NULL == h->current)
1116   {
1117     if (GNUNET_YES == h->do_destroy)
1118     {
1119       h->do_destroy = GNUNET_SYSERR; /* in 'TEST' mode */
1120       h->th = GNUNET_CLIENT_notify_transmit_ready (h->client,
1121                                                    sizeof (struct GNUNET_MessageHeader),
1122                                                    SET_TRANSMIT_TIMEOUT,
1123                                                    GNUNET_NO,
1124                                                    &transmit_test_on_shutdown, h);
1125     }
1126     return;
1127   }
1128   GNUNET_CONTAINER_DLL_remove (h->action_head, h->action_tail, h->current);
1129   timeout = GNUNET_TIME_absolute_get_remaining (h->current->timeout);
1130   if (NULL ==
1131       (h->th =
1132        GNUNET_CLIENT_notify_transmit_ready (h->client, h->current->msize,
1133                                             timeout, GNUNET_YES,
1134                                             &transmit_action, h)))
1135   {
1136     LOG (GNUNET_ERROR_TYPE_DEBUG,
1137          "Failed to transmit request to statistics service.\n");
1138     do_disconnect (h);
1139     reconnect_later (h);
1140   }
1141 }
1142
1143
1144 /**
1145  * Get statistic from the peer.
1146  *
1147  * @param handle identification of the statistics service
1148  * @param subsystem limit to the specified subsystem, NULL for our subsystem
1149  * @param name name of the statistic value, NULL for all values
1150  * @param timeout after how long should we give up (and call
1151  *        cont with an error code)?
1152  * @param cont continuation to call when done (can be NULL)
1153  *        This callback CANNOT destroy the statistics handle in the same call.
1154  * @param proc function to call on each value
1155  * @param cls closure for @a cont and @a proc
1156  * @return NULL on error
1157  */
1158 struct GNUNET_STATISTICS_GetHandle *
1159 GNUNET_STATISTICS_get (struct GNUNET_STATISTICS_Handle *handle,
1160                        const char *subsystem, const char *name,
1161                        struct GNUNET_TIME_Relative timeout,
1162                        GNUNET_STATISTICS_Callback cont,
1163                        GNUNET_STATISTICS_Iterator proc, void *cls)
1164 {
1165   size_t slen1;
1166   size_t slen2;
1167   struct GNUNET_STATISTICS_GetHandle *ai;
1168
1169   if (NULL == handle)
1170     return NULL;
1171   GNUNET_assert (NULL != proc);
1172   GNUNET_assert (GNUNET_NO == handle->do_destroy);
1173   if (NULL == subsystem)
1174     subsystem = "";
1175   if (NULL == name)
1176     name = "";
1177   slen1 = strlen (subsystem) + 1;
1178   slen2 = strlen (name) + 1;
1179   GNUNET_assert (slen1 + slen2 + sizeof (struct GNUNET_MessageHeader) <
1180                  GNUNET_SERVER_MAX_MESSAGE_SIZE);
1181   ai = GNUNET_new (struct GNUNET_STATISTICS_GetHandle);
1182   ai->sh = handle;
1183   ai->subsystem = GNUNET_strdup (subsystem);
1184   ai->name = GNUNET_strdup (name);
1185   ai->cont = cont;
1186   ai->proc = proc;
1187   ai->cls = cls;
1188   ai->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1189   ai->type = ACTION_GET;
1190   ai->msize = slen1 + slen2 + sizeof (struct GNUNET_MessageHeader);
1191   GNUNET_CONTAINER_DLL_insert_tail (handle->action_head, handle->action_tail,
1192                                     ai);
1193   schedule_action (handle);
1194   return ai;
1195 }
1196
1197
1198 /**
1199  * Cancel a 'get' request.  Must be called before the 'cont'
1200  * function is called.
1201  *
1202  * @param gh handle of the request to cancel
1203  */
1204 void
1205 GNUNET_STATISTICS_get_cancel (struct GNUNET_STATISTICS_GetHandle *gh)
1206 {
1207   if (NULL == gh)
1208     return;
1209   gh->cont = NULL;
1210   if (gh->sh->current == gh)
1211   {
1212     gh->aborted = GNUNET_YES;
1213   }
1214   else
1215   {
1216     GNUNET_CONTAINER_DLL_remove (gh->sh->action_head, gh->sh->action_tail, gh);
1217     GNUNET_free (gh->name);
1218     GNUNET_free (gh->subsystem);
1219     GNUNET_free (gh);
1220   }
1221 }
1222
1223
1224 /**
1225  * Watch statistics from the peer (be notified whenever they change).
1226  *
1227  * @param handle identification of the statistics service
1228  * @param subsystem limit to the specified subsystem, never NULL
1229  * @param name name of the statistic value, never NULL
1230  * @param proc function to call on each value
1231  * @param proc_cls closure for @a proc
1232  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1233  */
1234 int
1235 GNUNET_STATISTICS_watch (struct GNUNET_STATISTICS_Handle *handle,
1236                          const char *subsystem, const char *name,
1237                          GNUNET_STATISTICS_Iterator proc, void *proc_cls)
1238 {
1239   struct GNUNET_STATISTICS_WatchEntry *w;
1240
1241   if (NULL == handle)
1242     return GNUNET_SYSERR;
1243   w = GNUNET_new (struct GNUNET_STATISTICS_WatchEntry);
1244   w->subsystem = GNUNET_strdup (subsystem);
1245   w->name = GNUNET_strdup (name);
1246   w->proc = proc;
1247   w->proc_cls = proc_cls;
1248   GNUNET_array_append (handle->watches, handle->watches_size, w);
1249   schedule_watch_request (handle, w);
1250   return GNUNET_OK;
1251 }
1252
1253
1254 /**
1255  * Stop watching statistics from the peer.
1256  *
1257  * @param handle identification of the statistics service
1258  * @param subsystem limit to the specified subsystem, never NULL
1259  * @param name name of the statistic value, never NULL
1260  * @param proc function to call on each value
1261  * @param proc_cls closure for @a proc
1262  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error (no such watch)
1263  */
1264 int
1265 GNUNET_STATISTICS_watch_cancel (struct GNUNET_STATISTICS_Handle *handle,
1266                                 const char *subsystem,
1267                                 const char *name,
1268                                 GNUNET_STATISTICS_Iterator proc,
1269                                 void *proc_cls)
1270 {
1271   struct GNUNET_STATISTICS_WatchEntry *w;
1272   unsigned int i;
1273
1274   if (NULL == handle)
1275     return GNUNET_SYSERR;
1276   for (i=0;i<handle->watches_size;i++)
1277   {
1278     w = handle->watches[i];
1279     if (NULL == w)
1280       continue;
1281     if ( (w->proc == proc) &&
1282          (w->proc_cls == proc_cls) &&
1283          (0 == strcmp (w->name, name)) &&
1284          (0 == strcmp (w->subsystem, subsystem)) )
1285     {
1286       GNUNET_free (w->name);
1287       GNUNET_free (w->subsystem);
1288       GNUNET_free (w);
1289       handle->watches[i] = NULL;
1290       return GNUNET_OK;
1291     }
1292   }
1293   return GNUNET_SYSERR;
1294 }
1295
1296
1297
1298 /**
1299  * Queue a request to change a statistic.
1300  *
1301  * @param h statistics handle
1302  * @param name name of the value
1303  * @param make_persistent  should the value be kept across restarts?
1304  * @param value new value or change
1305  * @param type type of the action (#ACTION_SET or #ACTION_UPDATE)
1306  */
1307 static void
1308 add_setter_action (struct GNUNET_STATISTICS_Handle *h,
1309                    const char *name,
1310                    int make_persistent,
1311                    uint64_t value,
1312                    enum ActionType type)
1313 {
1314   struct GNUNET_STATISTICS_GetHandle *ai;
1315   size_t slen;
1316   size_t nlen;
1317   size_t nsize;
1318   int64_t delta;
1319
1320   slen = strlen (h->subsystem) + 1;
1321   nlen = strlen (name) + 1;
1322   nsize = sizeof (struct GNUNET_STATISTICS_SetMessage) + slen + nlen;
1323   if (nsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1324   {
1325     GNUNET_break (0);
1326     return;
1327   }
1328   for (ai = h->action_head; NULL != ai; ai = ai->next)
1329   {
1330     if (! ( (0 == strcmp (ai->subsystem, h->subsystem)) &&
1331             (0 == strcmp (ai->name, name)) &&
1332             ( (ACTION_UPDATE == ai->type) ||
1333               (ACTION_SET == ai->type) ) ) )
1334       continue;
1335     if (ACTION_SET == ai->type)
1336     {
1337       if (ACTION_UPDATE == type)
1338       {
1339         delta = (int64_t) value;
1340         if (delta > 0)
1341         {
1342           /* update old set by new delta */
1343           ai->value += delta;
1344         }
1345         else
1346         {
1347           /* update old set by new delta, but never go negative */
1348           if (ai->value < -delta)
1349             ai->value = 0;
1350           else
1351             ai->value += delta;
1352         }
1353       }
1354       else
1355       {
1356         /* new set overrides old set */
1357         ai->value = value;
1358       }
1359     }
1360     else
1361     {
1362       if (ACTION_UPDATE == type)
1363       {
1364         /* make delta cummulative */
1365         delta = (int64_t) value;
1366         ai->value += delta;
1367       }
1368       else
1369       {
1370         /* drop old 'update', use new 'set' instead */
1371         ai->value = value;
1372         ai->type = type;
1373       }
1374     }
1375     ai->timeout = GNUNET_TIME_relative_to_absolute (SET_TRANSMIT_TIMEOUT);
1376     ai->make_persistent = make_persistent;
1377     return;
1378   }
1379   /* no existing entry matches, create a fresh one */
1380   ai = GNUNET_new (struct GNUNET_STATISTICS_GetHandle);
1381   ai->sh = h;
1382   ai->subsystem = GNUNET_strdup (h->subsystem);
1383   ai->name = GNUNET_strdup (name);
1384   ai->timeout = GNUNET_TIME_relative_to_absolute (SET_TRANSMIT_TIMEOUT);
1385   ai->make_persistent = make_persistent;
1386   ai->msize = nsize;
1387   ai->value = value;
1388   ai->type = type;
1389   GNUNET_CONTAINER_DLL_insert_tail (h->action_head, h->action_tail,
1390                                     ai);
1391   schedule_action (h);
1392 }
1393
1394
1395 /**
1396  * Set statistic value for the peer.  Will always use our
1397  * subsystem (the argument used when "handle" was created).
1398  *
1399  * @param handle identification of the statistics service
1400  * @param name name of the statistic value
1401  * @param value new value to set
1402  * @param make_persistent should the value be kept across restarts?
1403  */
1404 void
1405 GNUNET_STATISTICS_set (struct GNUNET_STATISTICS_Handle *handle,
1406                        const char *name,
1407                        uint64_t value,
1408                        int make_persistent)
1409 {
1410   if (NULL == handle)
1411     return;
1412   GNUNET_assert (GNUNET_NO == handle->do_destroy);
1413   add_setter_action (handle, name, make_persistent, value, ACTION_SET);
1414 }
1415
1416
1417 /**
1418  * Set statistic value for the peer.  Will always use our
1419  * subsystem (the argument used when "handle" was created).
1420  *
1421  * @param handle identification of the statistics service
1422  * @param name name of the statistic value
1423  * @param delta change in value (added to existing value)
1424  * @param make_persistent should the value be kept across restarts?
1425  */
1426 void
1427 GNUNET_STATISTICS_update (struct GNUNET_STATISTICS_Handle *handle,
1428                           const char *name,
1429                           int64_t delta,
1430                           int make_persistent)
1431 {
1432   if (NULL == handle)
1433     return;
1434   if (0 == delta)
1435     return;
1436   GNUNET_assert (GNUNET_NO == handle->do_destroy);
1437   add_setter_action (handle,
1438                      name,
1439                      make_persistent,
1440                      (uint64_t) delta,
1441                      ACTION_UPDATE);
1442 }
1443
1444
1445 /* end of statistics_api.c */