04e85a07e95323b65d2026990c05d66c836e306b
[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
330   struct GNUNET_STATISTICS_GetHandle *ai;
331   size_t slen;
332   size_t nlen;
333   size_t nsize;
334
335   GNUNET_assert (NULL != h);
336   GNUNET_assert (NULL != watch);
337
338   slen = strlen (watch->subsystem) + 1;
339   nlen = strlen (watch->name) + 1;
340   nsize = sizeof (struct GNUNET_MessageHeader) + slen + nlen;
341   if (nsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
342   {
343     GNUNET_break (0);
344     return;
345   }
346   ai = GNUNET_new (struct GNUNET_STATISTICS_GetHandle);
347   ai->sh = h;
348   ai->subsystem = GNUNET_strdup (watch->subsystem);
349   ai->name = GNUNET_strdup (watch->name);
350   ai->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
351   ai->msize = nsize;
352   ai->type = ACTION_WATCH;
353   ai->proc = watch->proc;
354   ai->cls = watch->proc_cls;
355   GNUNET_CONTAINER_DLL_insert_tail (h->action_head, h->action_tail,
356                                     ai);
357   schedule_action (h);
358 }
359
360
361 /**
362  * Free memory associated with the given action item.
363  *
364  * @param gh action item to free
365  */
366 static void
367 free_action_item (struct GNUNET_STATISTICS_GetHandle *gh)
368 {
369   GNUNET_free_non_null (gh->subsystem);
370   GNUNET_free_non_null (gh->name);
371   GNUNET_free (gh);
372 }
373
374
375 /**
376  * Disconnect from the statistics service.
377  *
378  * @param h statistics handle to disconnect from
379  */
380 static void
381 do_disconnect (struct GNUNET_STATISTICS_Handle *h)
382 {
383   struct GNUNET_STATISTICS_GetHandle *c;
384
385   if (NULL != h->th)
386   {
387     GNUNET_CLIENT_notify_transmit_ready_cancel (h->th);
388     h->th = NULL;
389   }
390   h->receiving = GNUNET_NO;
391   if (NULL != (c = h->current))
392   {
393     h->current = NULL;
394     if ( (NULL != c->cont) &&
395          (GNUNET_YES != c->aborted) )
396       c->cont (c->cls, GNUNET_SYSERR);
397     free_action_item (c);
398   }
399   if (NULL != h->client)
400   {
401     GNUNET_CLIENT_disconnect (h->client);
402     h->client = NULL;
403   }
404 }
405
406
407 /**
408  * Try to (re)connect to the statistics service.
409  *
410  * @param h statistics handle to reconnect
411  * @return #GNUNET_YES on success, #GNUNET_NO on failure.
412  */
413 static int
414 try_connect (struct GNUNET_STATISTICS_Handle *h)
415 {
416   struct GNUNET_STATISTICS_GetHandle *gh;
417   struct GNUNET_STATISTICS_GetHandle *gn;
418   unsigned int i;
419
420   if (GNUNET_SCHEDULER_NO_TASK != h->backoff_task)
421     return GNUNET_NO;
422   if (NULL != h->client)
423     return GNUNET_YES;
424   h->client = GNUNET_CLIENT_connect ("statistics", h->cfg);
425   if (NULL != h->client)
426   {
427     gn = h->action_head;
428     while (NULL != (gh = gn))
429     {
430       gn = gh->next;
431       if (gh->type == ACTION_WATCH)
432       {
433         GNUNET_CONTAINER_DLL_remove (h->action_head,
434                                      h->action_tail,
435                                      gh);
436         free_action_item (gh);
437       }
438     }
439     for (i = 0; i < h->watches_size; i++)
440     {
441       if (NULL != h->watches[i])
442         schedule_watch_request (h, h->watches[i]);
443     }
444     return GNUNET_YES;
445   }
446   LOG (GNUNET_ERROR_TYPE_DEBUG,
447        "Failed to connect to statistics service!\n");
448   return GNUNET_NO;
449 }
450
451
452 /**
453  * We've waited long enough, reconnect now.
454  *
455  * @param cls the 'struct GNUNET_STATISTICS_Handle' to reconnect
456  * @param tc scheduler context (unused)
457  */
458 static void
459 reconnect_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
460 {
461   struct GNUNET_STATISTICS_Handle *h = cls;
462
463   h->backoff_task = GNUNET_SCHEDULER_NO_TASK;
464   schedule_action (h);
465 }
466
467
468 /**
469  * Task used by 'reconnect_later' to shutdown the handle
470  *
471  * @param cls the statistics handle
472  * @param tc scheduler context
473  */
474 static void
475 do_destroy (void *cls,
476                const struct GNUNET_SCHEDULER_TaskContext *tc)
477 {
478   struct GNUNET_STATISTICS_Handle *h = cls;
479
480   GNUNET_STATISTICS_destroy (h, GNUNET_NO);
481 }
482
483
484 /**
485  * Reconnect at a later time, respecting back-off.
486  *
487  * @param h statistics handle
488  */
489 static void
490 reconnect_later (struct GNUNET_STATISTICS_Handle *h)
491 {
492   int loss;
493   struct GNUNET_STATISTICS_GetHandle *gh;
494
495   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == h->backoff_task);
496   if (GNUNET_YES == h->do_destroy)
497   {
498     /* So we are shutting down and the service is not reachable.
499      * Chances are that it's down for good and we are not going to connect to
500      * it anymore.
501      * Give up and don't sync the rest of the data.
502      */
503     loss = GNUNET_NO;
504     for (gh = h->action_head; NULL != gh; gh = gh->next)
505       if ( (gh->make_persistent) && (ACTION_SET == gh->type) )
506         loss = GNUNET_YES;
507     if (GNUNET_YES == loss)
508       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
509                   _("Could not save some persistent statistics\n"));
510     h->do_destroy = GNUNET_NO;
511     GNUNET_SCHEDULER_add_continuation (&do_destroy, h,
512                                        GNUNET_SCHEDULER_REASON_PREREQ_DONE);
513     return;
514   }
515   h->backoff_task =
516     GNUNET_SCHEDULER_add_delayed (h->backoff, &reconnect_task, h);
517   h->backoff = GNUNET_TIME_STD_BACKOFF (h->backoff);
518 }
519
520
521 /**
522  * Process a 'GNUNET_MESSAGE_TYPE_STATISTICS_VALUE' message.
523  *
524  * @param h statistics handle
525  * @param msg message received from the service, never NULL
526  * @return GNUNET_OK if the message was well-formed
527  */
528 static int
529 process_statistics_value_message (struct GNUNET_STATISTICS_Handle *h,
530                                   const struct GNUNET_MessageHeader *msg)
531 {
532   char *service;
533   char *name;
534   const struct GNUNET_STATISTICS_ReplyMessage *smsg;
535   uint16_t size;
536
537   if (h->current->aborted)
538   {
539     LOG (GNUNET_ERROR_TYPE_DEBUG, "Iteration was aborted, ignoring VALUE\n");
540     return GNUNET_OK;           /* don't bother */
541   }
542   size = ntohs (msg->size);
543   if (size < sizeof (struct GNUNET_STATISTICS_ReplyMessage))
544   {
545     GNUNET_break (0);
546     return GNUNET_SYSERR;
547   }
548   smsg = (const struct GNUNET_STATISTICS_ReplyMessage *) msg;
549   size -= sizeof (struct GNUNET_STATISTICS_ReplyMessage);
550   if (size !=
551       GNUNET_STRINGS_buffer_tokenize ((const char *) &smsg[1], size, 2,
552                                       &service, &name))
553   {
554     GNUNET_break (0);
555     return GNUNET_SYSERR;
556   }
557   LOG (GNUNET_ERROR_TYPE_DEBUG, "Received valid statistic on `%s:%s': %llu\n",
558        service, name, 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, "VALUE processed successfully\n");
570   return GNUNET_OK;
571 }
572
573
574 /**
575  * We have received a watch value from the service.  Process it.
576  *
577  * @param h statistics handle
578  * @param msg the watch value message
579  * @return GNUNET_OK if the message was well-formed, GNUNET_SYSERR if not,
580  *         GNUNET_NO if this watch has been cancelled
581  */
582 static int
583 process_watch_value (struct GNUNET_STATISTICS_Handle *h,
584                      const struct GNUNET_MessageHeader *msg)
585 {
586   const struct GNUNET_STATISTICS_WatchValueMessage *wvm;
587   struct GNUNET_STATISTICS_WatchEntry *w;
588   uint32_t wid;
589
590   if (sizeof (struct GNUNET_STATISTICS_WatchValueMessage) != ntohs (msg->size))
591   {
592     GNUNET_break (0);
593     return GNUNET_SYSERR;
594   }
595   wvm = (const struct GNUNET_STATISTICS_WatchValueMessage *) msg;
596   GNUNET_break (0 == ntohl (wvm->reserved));
597   wid = ntohl (wvm->wid);
598   if (wid >= h->watches_size)
599   {
600     GNUNET_break (0);
601     return GNUNET_SYSERR;
602   }
603   w = h->watches[wid];
604   if (NULL == w)
605     return GNUNET_NO;
606   (void) w->proc (w->proc_cls, w->subsystem, w->name,
607                   GNUNET_ntohll (wvm->value),
608                   0 != (ntohl (wvm->flags) & GNUNET_STATISTICS_PERSIST_BIT));
609   return GNUNET_OK;
610 }
611
612
613 static void
614 destroy_task (void *cls,
615               const struct GNUNET_SCHEDULER_TaskContext *tc)
616 {
617   struct GNUNET_STATISTICS_Handle *h = cls;
618
619   GNUNET_STATISTICS_destroy (h, GNUNET_NO);
620 }
621
622
623 /**
624  * Function called with messages from stats service.
625  *
626  * @param cls closure
627  * @param msg message received, NULL on timeout or fatal error
628  */
629 static void
630 receive_stats (void *cls, const struct GNUNET_MessageHeader *msg)
631 {
632   struct GNUNET_STATISTICS_Handle *h = cls;
633   struct GNUNET_STATISTICS_GetHandle *c;
634   int ret;
635
636   if (NULL == msg)
637   {
638     LOG (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
639          "Error receiving statistics from service, is the service running?\n");
640     do_disconnect (h);
641     reconnect_later (h);
642     return;
643   }
644   switch (ntohs (msg->type))
645   {
646   case GNUNET_MESSAGE_TYPE_TEST:
647     if (GNUNET_SYSERR != h->do_destroy)
648     {
649       /* not in shutdown, why do we get 'TEST'? */
650       GNUNET_break (0);
651       do_disconnect (h);
652       reconnect_later (h);
653       return;
654     }
655     h->do_destroy = GNUNET_NO;
656     GNUNET_SCHEDULER_add_continuation (&destroy_task, h,
657                                        GNUNET_SCHEDULER_REASON_PREREQ_DONE);
658     break;
659   case GNUNET_MESSAGE_TYPE_STATISTICS_END:
660     LOG (GNUNET_ERROR_TYPE_DEBUG, "Received end of statistics marker\n");
661     if (NULL == (c = h->current))
662     {
663       GNUNET_break (0);
664       do_disconnect (h);
665       reconnect_later (h);
666       return;
667     }
668     h->backoff = GNUNET_TIME_UNIT_MILLISECONDS;
669     if (h->watches_size > 0)
670     {
671       GNUNET_CLIENT_receive (h->client, &receive_stats, h,
672                              GNUNET_TIME_UNIT_FOREVER_REL);
673     }
674     else
675     {
676       h->receiving = GNUNET_NO;
677     }
678     h->current = NULL;
679     schedule_action (h);
680     if (NULL != c->cont)
681       c->cont (c->cls, GNUNET_OK);
682     free_action_item (c);
683     return;
684   case GNUNET_MESSAGE_TYPE_STATISTICS_VALUE:
685     if (GNUNET_OK != process_statistics_value_message (h, msg))
686     {
687       do_disconnect (h);
688       reconnect_later (h);
689       return;
690     }
691     /* finally, look for more! */
692     LOG (GNUNET_ERROR_TYPE_DEBUG,
693          "Processing VALUE done, now reading more\n");
694     GNUNET_CLIENT_receive (h->client, &receive_stats, h,
695                            GNUNET_TIME_absolute_get_remaining (h->
696                                                                current->timeout));
697     h->backoff = GNUNET_TIME_UNIT_MILLISECONDS;
698     return;
699   case GNUNET_MESSAGE_TYPE_STATISTICS_WATCH_VALUE:
700     if (GNUNET_OK !=
701         (ret = process_watch_value (h, msg)))
702     {
703       do_disconnect (h);
704       if (GNUNET_NO == ret)
705         h->backoff = GNUNET_TIME_UNIT_MILLISECONDS;
706       reconnect_later (h);
707       return;
708     }
709     h->backoff = GNUNET_TIME_UNIT_MILLISECONDS;
710     GNUNET_assert (h->watches_size > 0);
711     GNUNET_CLIENT_receive (h->client, &receive_stats, h,
712                            GNUNET_TIME_UNIT_FOREVER_REL);
713     return;
714   default:
715     GNUNET_break (0);
716     do_disconnect (h);
717     reconnect_later (h);
718     return;
719   }
720 }
721
722
723 /**
724  * Transmit a GET request (and if successful, start to receive
725  * the response).
726  *
727  * @param handle statistics handle
728  * @param size how many bytes can we write to buf
729  * @param buf where to write requests to the service
730  * @return number of bytes written to buf
731  */
732 static size_t
733 transmit_get (struct GNUNET_STATISTICS_Handle *handle, size_t size, void *buf)
734 {
735   struct GNUNET_STATISTICS_GetHandle *c;
736   struct GNUNET_MessageHeader *hdr;
737   size_t slen1;
738   size_t slen2;
739   uint16_t msize;
740
741   GNUNET_assert (NULL != (c = handle->current));
742   if (NULL == buf)
743   {
744     /* timeout / error */
745     LOG (GNUNET_ERROR_TYPE_DEBUG,
746          "Transmission of request for statistics failed!\n");
747     do_disconnect (handle);
748     reconnect_later (handle);
749     return 0;
750   }
751   slen1 = strlen (c->subsystem) + 1;
752   slen2 = strlen (c->name) + 1;
753   msize = slen1 + slen2 + sizeof (struct GNUNET_MessageHeader);
754   GNUNET_assert (msize <= size);
755   hdr = (struct GNUNET_MessageHeader *) buf;
756   hdr->size = htons (msize);
757   hdr->type = htons (GNUNET_MESSAGE_TYPE_STATISTICS_GET);
758   GNUNET_assert (slen1 + slen2 ==
759                  GNUNET_STRINGS_buffer_fill ((char *) &hdr[1], slen1 + slen2, 2,
760                                              c->subsystem,
761                                              c->name));
762   if (GNUNET_YES != handle->receiving)
763   {
764     LOG (GNUNET_ERROR_TYPE_DEBUG,
765          "Transmission of GET done, now reading response\n");
766     handle->receiving = GNUNET_YES;
767     GNUNET_CLIENT_receive (handle->client, &receive_stats, handle,
768                            GNUNET_TIME_absolute_get_remaining (c->timeout));
769   }
770   return msize;
771 }
772
773
774 /**
775  * Transmit a WATCH request (and if successful, start to receive
776  * the response).
777  *
778  * @param handle statistics handle
779  * @param size how many bytes can we write to buf
780  * @param buf where to write requests to the service
781  * @return number of bytes written to buf
782  */
783 static size_t
784 transmit_watch (struct GNUNET_STATISTICS_Handle *handle, size_t size, void *buf)
785 {
786   struct GNUNET_MessageHeader *hdr;
787   size_t slen1;
788   size_t slen2;
789   uint16_t msize;
790
791   if (NULL == buf)
792   {
793     /* timeout / error */
794     LOG (GNUNET_ERROR_TYPE_DEBUG,
795          "Transmission of request for statistics failed!\n");
796     do_disconnect (handle);
797     reconnect_later (handle);
798     return 0;
799   }
800   LOG (GNUNET_ERROR_TYPE_DEBUG, "Transmitting watch request for `%s'\n",
801        handle->current->name);
802   slen1 = strlen (handle->current->subsystem) + 1;
803   slen2 = strlen (handle->current->name) + 1;
804   msize = slen1 + slen2 + sizeof (struct GNUNET_MessageHeader);
805   GNUNET_assert (msize <= size);
806   hdr = (struct GNUNET_MessageHeader *) buf;
807   hdr->size = htons (msize);
808   hdr->type = htons (GNUNET_MESSAGE_TYPE_STATISTICS_WATCH);
809   GNUNET_assert (slen1 + slen2 ==
810                  GNUNET_STRINGS_buffer_fill ((char *) &hdr[1], slen1 + slen2, 2,
811                                              handle->current->subsystem,
812                                              handle->current->name));
813   if (GNUNET_YES != handle->receiving)
814   {
815     handle->receiving = GNUNET_YES;
816     GNUNET_CLIENT_receive (handle->client, &receive_stats, handle,
817                            GNUNET_TIME_UNIT_FOREVER_REL);
818   }
819   GNUNET_assert (NULL == handle->current->cont);
820   free_action_item (handle->current);
821   handle->current = NULL;
822   return msize;
823 }
824
825
826 /**
827  * Transmit a SET/UPDATE request.
828  *
829  * @param handle statistics handle
830  * @param size how many bytes can we write to buf
831  * @param buf where to write requests to the service
832  * @return number of bytes written to buf
833  */
834 static size_t
835 transmit_set (struct GNUNET_STATISTICS_Handle *handle, size_t size, void *buf)
836 {
837   struct GNUNET_STATISTICS_SetMessage *r;
838   size_t slen;
839   size_t nlen;
840   size_t nsize;
841
842   if (NULL == buf)
843   {
844     do_disconnect (handle);
845     reconnect_later (handle);
846     return 0;
847   }
848   slen = strlen (handle->current->subsystem) + 1;
849   nlen = strlen (handle->current->name) + 1;
850   nsize = sizeof (struct GNUNET_STATISTICS_SetMessage) + slen + nlen;
851   if (size < nsize)
852   {
853     GNUNET_break (0);
854     do_disconnect (handle);
855     reconnect_later (handle);
856     return 0;
857   }
858   r = buf;
859   r->header.size = htons (nsize);
860   r->header.type = htons (GNUNET_MESSAGE_TYPE_STATISTICS_SET);
861   r->flags = 0;
862   r->value = GNUNET_htonll (handle->current->value);
863   if (handle->current->make_persistent)
864     r->flags |= htonl (GNUNET_STATISTICS_SETFLAG_PERSISTENT);
865   if (handle->current->type == ACTION_UPDATE)
866     r->flags |= htonl (GNUNET_STATISTICS_SETFLAG_RELATIVE);
867   GNUNET_assert (slen + nlen ==
868                  GNUNET_STRINGS_buffer_fill ((char *) &r[1], slen + nlen, 2,
869                                              handle->current->subsystem,
870                                              handle->current->name));
871   GNUNET_assert (NULL == handle->current->cont);
872   free_action_item (handle->current);
873   handle->current = NULL;
874   update_memory_statistics (handle);
875   return nsize;
876 }
877
878
879 /**
880  * Function called when we are ready to transmit a request to the service.
881  *
882  * @param cls the 'struct GNUNET_STATISTICS_Handle'
883  * @param size how many bytes can we write to buf
884  * @param buf where to write requests to the service
885  * @return number of bytes written to buf
886  */
887 static size_t
888 transmit_action (void *cls, size_t size, void *buf)
889 {
890   struct GNUNET_STATISTICS_Handle *h = cls;
891   size_t ret;
892
893   h->th = NULL;
894   ret = 0;
895   if (NULL != h->current)
896     switch (h->current->type)
897     {
898     case ACTION_GET:
899       ret = transmit_get (h, size, buf);
900       break;
901     case ACTION_SET:
902     case ACTION_UPDATE:
903       ret = transmit_set (h, size, buf);
904       break;
905     case ACTION_WATCH:
906       ret = transmit_watch (h, size, buf);
907       break;
908     default:
909       GNUNET_assert (0);
910       break;
911     }
912   schedule_action (h);
913   return ret;
914 }
915
916
917 /**
918  * Get handle for the statistics service.
919  *
920  * @param subsystem name of subsystem using the service
921  * @param cfg services configuration in use
922  * @return handle to use
923  */
924 struct GNUNET_STATISTICS_Handle *
925 GNUNET_STATISTICS_create (const char *subsystem,
926                           const struct GNUNET_CONFIGURATION_Handle *cfg)
927 {
928   struct GNUNET_STATISTICS_Handle *ret;
929
930   if (GNUNET_YES ==
931       GNUNET_CONFIGURATION_get_value_yesno (cfg, "statistics", "DISABLE"))
932     return NULL;
933   GNUNET_assert (NULL != subsystem);
934   GNUNET_assert (NULL != cfg);
935   ret = GNUNET_new (struct GNUNET_STATISTICS_Handle);
936   ret->cfg = cfg;
937   ret->subsystem = GNUNET_strdup (subsystem);
938   ret->backoff = GNUNET_TIME_UNIT_MILLISECONDS;
939   return ret;
940 }
941
942
943 /**
944  * Destroy a handle (free all state associated with
945  * it).
946  *
947  * @param h statistics handle to destroy
948  * @param sync_first set to GNUNET_YES if pending SET requests should
949  *        be completed
950  */
951 void
952 GNUNET_STATISTICS_destroy (struct GNUNET_STATISTICS_Handle *h, int sync_first)
953 {
954   struct GNUNET_STATISTICS_GetHandle *pos;
955   struct GNUNET_STATISTICS_GetHandle *next;
956   struct GNUNET_TIME_Relative timeout;
957   int i;
958
959   if (NULL == h)
960     return;
961   GNUNET_assert (GNUNET_NO == h->do_destroy); // Don't call twice.
962   if (GNUNET_SCHEDULER_NO_TASK != h->backoff_task)
963   {
964     GNUNET_SCHEDULER_cancel (h->backoff_task);
965     h->backoff_task = GNUNET_SCHEDULER_NO_TASK;
966   }
967   if (sync_first)
968   {
969     if (NULL != h->current)
970     {
971       if (ACTION_GET == h->current->type)
972       {
973         GNUNET_CLIENT_notify_transmit_ready_cancel (h->th);
974         h->th = NULL;
975         free_action_item (h->current);
976         h->current = NULL;
977       }
978     }
979     next = h->action_head;
980     while (NULL != (pos = next))
981     {
982       next = pos->next;
983       if (ACTION_GET == pos->type)
984       {
985         GNUNET_CONTAINER_DLL_remove (h->action_head,
986                                      h->action_tail,
987                                      pos);
988         free_action_item (pos);
989       }
990     }
991     if ( (NULL == h->current) &&
992          (NULL != (h->current = h->action_head)) )
993       GNUNET_CONTAINER_DLL_remove (h->action_head,
994                                    h->action_tail,
995                                    h->current);
996     h->do_destroy = GNUNET_YES;
997     if ((NULL != h->current) && (NULL == h->th) &&
998         (NULL != h->client))
999     {
1000       timeout = GNUNET_TIME_absolute_get_remaining (h->current->timeout);
1001       h->th =
1002         GNUNET_CLIENT_notify_transmit_ready (h->client, h->current->msize,
1003                                              timeout, GNUNET_YES,
1004                                              &transmit_action, h);
1005       GNUNET_assert (NULL != h->th);
1006     }
1007     if (NULL != h->th)
1008       return; /* do not finish destruction just yet */
1009   }
1010   while (NULL != (pos = h->action_head))
1011   {
1012     GNUNET_CONTAINER_DLL_remove (h->action_head,
1013                                  h->action_tail,
1014                                  pos);
1015     free_action_item (pos);
1016   }
1017   do_disconnect (h);
1018   for (i = 0; i < h->watches_size; i++)
1019   {
1020     if (NULL == h->watches[i])
1021       continue;
1022     GNUNET_free (h->watches[i]->subsystem);
1023     GNUNET_free (h->watches[i]->name);
1024     GNUNET_free (h->watches[i]);
1025   }
1026   GNUNET_array_grow (h->watches, h->watches_size, 0);
1027   GNUNET_free (h->subsystem);
1028   GNUNET_free (h);
1029 }
1030
1031
1032 /**
1033  * Function called to transmit TEST message to service to
1034  * confirm that the service has received all of our 'SET'
1035  * messages (during statistics disconnect/shutdown).
1036  *
1037  * @param cls the 'struct GNUNET_STATISTICS_Handle'
1038  * @param size how many bytes can we write to buf
1039  * @param buf where to write requests to the service
1040  * @return number of bytes written to buf
1041  */
1042 static size_t
1043 transmit_test_on_shutdown (void *cls,
1044                            size_t size,
1045                            void *buf)
1046 {
1047   struct GNUNET_STATISTICS_Handle *h = cls;
1048   struct GNUNET_MessageHeader hdr;
1049
1050   h->th = NULL;
1051   if (NULL == buf)
1052   {
1053     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1054                 _("Failed to receive acknowledgement from statistics service, some statistics might have been lost!\n"));
1055     h->do_destroy = GNUNET_NO;
1056     GNUNET_SCHEDULER_add_continuation (&destroy_task, h,
1057                                        GNUNET_SCHEDULER_REASON_PREREQ_DONE);
1058     return 0;
1059   }
1060   hdr.type = htons (GNUNET_MESSAGE_TYPE_TEST);
1061   hdr.size = htons (sizeof (struct GNUNET_MessageHeader));
1062   memcpy (buf, &hdr, sizeof (hdr));
1063   if (GNUNET_YES != h->receiving)
1064   {
1065     h->receiving = GNUNET_YES;
1066     GNUNET_CLIENT_receive (h->client, &receive_stats, h,
1067                            GNUNET_TIME_UNIT_FOREVER_REL);
1068   }
1069   return sizeof (struct GNUNET_MessageHeader);
1070 }
1071
1072
1073 /**
1074  * Schedule the next action to be performed.
1075  *
1076  * @param h statistics handle
1077  */
1078 static void
1079 schedule_action (struct GNUNET_STATISTICS_Handle *h)
1080 {
1081   struct GNUNET_TIME_Relative timeout;
1082
1083   if ( (NULL != h->th) ||
1084        (GNUNET_SCHEDULER_NO_TASK != h->backoff_task) )
1085     return;                     /* action already pending */
1086   if (GNUNET_YES != try_connect (h))
1087   {
1088     reconnect_later (h);
1089     return;
1090   }
1091   if (NULL != h->current)
1092     return; /* action already pending */
1093   /* schedule next action */
1094   h->current = h->action_head;
1095   if (NULL == h->current)
1096   {
1097     if (GNUNET_YES == h->do_destroy)
1098     {
1099       h->do_destroy = GNUNET_SYSERR; /* in 'TEST' mode */
1100       h->th = GNUNET_CLIENT_notify_transmit_ready (h->client,
1101                                                    sizeof (struct GNUNET_MessageHeader),
1102                                                    SET_TRANSMIT_TIMEOUT,
1103                                                    GNUNET_NO,
1104                                                    &transmit_test_on_shutdown, h);
1105     }
1106     return;
1107   }
1108   GNUNET_CONTAINER_DLL_remove (h->action_head, h->action_tail, h->current);
1109   timeout = GNUNET_TIME_absolute_get_remaining (h->current->timeout);
1110   if (NULL ==
1111       (h->th =
1112        GNUNET_CLIENT_notify_transmit_ready (h->client, h->current->msize,
1113                                             timeout, GNUNET_YES,
1114                                             &transmit_action, h)))
1115   {
1116     LOG (GNUNET_ERROR_TYPE_DEBUG,
1117          "Failed to transmit request to statistics service.\n");
1118     do_disconnect (h);
1119     reconnect_later (h);
1120   }
1121 }
1122
1123
1124 /**
1125  * Get statistic from the peer.
1126  *
1127  * @param handle identification of the statistics service
1128  * @param subsystem limit to the specified subsystem, NULL for our subsystem
1129  * @param name name of the statistic value, NULL for all values
1130  * @param timeout after how long should we give up (and call
1131  *        cont with an error code)?
1132  * @param cont continuation to call when done (can be NULL)
1133  *        This callback CANNOT destroy the statistics handle in the same call.
1134  * @param proc function to call on each value
1135  * @param cls closure for cont and proc
1136  * @return NULL on error
1137  */
1138 struct GNUNET_STATISTICS_GetHandle *
1139 GNUNET_STATISTICS_get (struct GNUNET_STATISTICS_Handle *handle,
1140                        const char *subsystem, const char *name,
1141                        struct GNUNET_TIME_Relative timeout,
1142                        GNUNET_STATISTICS_Callback cont,
1143                        GNUNET_STATISTICS_Iterator proc, void *cls)
1144 {
1145   size_t slen1;
1146   size_t slen2;
1147   struct GNUNET_STATISTICS_GetHandle *ai;
1148
1149   if (NULL == handle)
1150     return NULL;
1151   GNUNET_assert (NULL != proc);
1152   GNUNET_assert (GNUNET_NO == handle->do_destroy);
1153   if (NULL == subsystem)
1154     subsystem = "";
1155   if (NULL == name)
1156     name = "";
1157   slen1 = strlen (subsystem) + 1;
1158   slen2 = strlen (name) + 1;
1159   GNUNET_assert (slen1 + slen2 + sizeof (struct GNUNET_MessageHeader) <
1160                  GNUNET_SERVER_MAX_MESSAGE_SIZE);
1161   ai = GNUNET_new (struct GNUNET_STATISTICS_GetHandle);
1162   ai->sh = handle;
1163   ai->subsystem = GNUNET_strdup (subsystem);
1164   ai->name = GNUNET_strdup (name);
1165   ai->cont = cont;
1166   ai->proc = proc;
1167   ai->cls = cls;
1168   ai->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1169   ai->type = ACTION_GET;
1170   ai->msize = slen1 + slen2 + sizeof (struct GNUNET_MessageHeader);
1171   GNUNET_CONTAINER_DLL_insert_tail (handle->action_head, handle->action_tail,
1172                                     ai);
1173   schedule_action (handle);
1174   return ai;
1175 }
1176
1177
1178 /**
1179  * Cancel a 'get' request.  Must be called before the 'cont'
1180  * function is called.
1181  *
1182  * @param gh handle of the request to cancel
1183  */
1184 void
1185 GNUNET_STATISTICS_get_cancel (struct GNUNET_STATISTICS_GetHandle *gh)
1186 {
1187   if (NULL == gh)
1188     return;
1189   gh->cont = NULL;
1190   if (gh->sh->current == gh)
1191   {
1192     gh->aborted = GNUNET_YES;
1193   }
1194   else
1195   {
1196     GNUNET_CONTAINER_DLL_remove (gh->sh->action_head, gh->sh->action_tail, gh);
1197     GNUNET_free (gh->name);
1198     GNUNET_free (gh->subsystem);
1199     GNUNET_free (gh);
1200   }
1201 }
1202
1203
1204 /**
1205  * Watch statistics from the peer (be notified whenever they change).
1206  *
1207  * @param handle identification of the statistics service
1208  * @param subsystem limit to the specified subsystem, never NULL
1209  * @param name name of the statistic value, never NULL
1210  * @param proc function to call on each value
1211  * @param proc_cls closure for proc
1212  * @return GNUNET_OK on success, GNUNET_SYSERR on error
1213  */
1214 int
1215 GNUNET_STATISTICS_watch (struct GNUNET_STATISTICS_Handle *handle,
1216                          const char *subsystem, const char *name,
1217                          GNUNET_STATISTICS_Iterator proc, void *proc_cls)
1218 {
1219   struct GNUNET_STATISTICS_WatchEntry *w;
1220
1221   if (NULL == handle)
1222     return GNUNET_SYSERR;
1223   w = GNUNET_new (struct GNUNET_STATISTICS_WatchEntry);
1224   w->subsystem = GNUNET_strdup (subsystem);
1225   w->name = GNUNET_strdup (name);
1226   w->proc = proc;
1227   w->proc_cls = proc_cls;
1228   GNUNET_array_append (handle->watches, handle->watches_size, w);
1229   schedule_watch_request (handle, w);
1230   return GNUNET_OK;
1231 }
1232
1233
1234 /**
1235  * Stop watching statistics from the peer.
1236  *
1237  * @param handle identification of the statistics service
1238  * @param subsystem limit to the specified subsystem, never NULL
1239  * @param name name of the statistic value, never NULL
1240  * @param proc function to call on each value
1241  * @param proc_cls closure for proc
1242  * @return GNUNET_OK on success, GNUNET_SYSERR on error (no such watch)
1243  */
1244 int
1245 GNUNET_STATISTICS_watch_cancel (struct GNUNET_STATISTICS_Handle *handle,
1246                                 const char *subsystem, const char *name,
1247                                 GNUNET_STATISTICS_Iterator proc, void *proc_cls)
1248 {
1249   struct GNUNET_STATISTICS_WatchEntry *w;
1250   unsigned int i;
1251
1252   if (NULL == handle)
1253     return GNUNET_SYSERR;
1254   for (i=0;i<handle->watches_size;i++)
1255   {
1256     w = handle->watches[i];
1257     if (NULL == w)
1258       continue;
1259     if ( (w->proc == proc) &&
1260          (w->proc_cls == proc_cls) &&
1261          (0 == strcmp (w->name, name)) &&
1262          (0 == strcmp (w->subsystem, subsystem)) )
1263     {
1264       GNUNET_free (w->name);
1265       GNUNET_free (w->subsystem);
1266       GNUNET_free (w);
1267       handle->watches[i] = NULL;
1268       return GNUNET_OK;
1269     }
1270   }
1271   return GNUNET_SYSERR;
1272 }
1273
1274
1275
1276 /**
1277  * Queue a request to change a statistic.
1278  *
1279  * @param h statistics handle
1280  * @param name name of the value
1281  * @param make_persistent  should the value be kept across restarts?
1282  * @param value new value or change
1283  * @param type type of the action (ACTION_SET or ACTION_UPDATE)
1284  */
1285 static void
1286 add_setter_action (struct GNUNET_STATISTICS_Handle *h, const char *name,
1287                    int make_persistent, uint64_t value, enum ActionType type)
1288 {
1289   struct GNUNET_STATISTICS_GetHandle *ai;
1290   size_t slen;
1291   size_t nlen;
1292   size_t nsize;
1293   int64_t delta;
1294
1295   GNUNET_assert (NULL != h);
1296   GNUNET_assert (NULL != name);
1297   slen = strlen (h->subsystem) + 1;
1298   nlen = strlen (name) + 1;
1299   nsize = sizeof (struct GNUNET_STATISTICS_SetMessage) + slen + nlen;
1300   if (nsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1301   {
1302     GNUNET_break (0);
1303     return;
1304   }
1305   for (ai = h->action_head; NULL != ai; ai = ai->next)
1306   {
1307     if (! ( (0 == strcmp (ai->subsystem, h->subsystem)) &&
1308             (0 == strcmp (ai->name, name)) &&
1309             ( (ACTION_UPDATE == ai->type) ||
1310               (ACTION_SET == ai->type) ) ) )
1311       continue;
1312     if (ACTION_SET == ai->type)
1313     {
1314       if (ACTION_UPDATE == type)
1315       {
1316         delta = (int64_t) value;
1317         if (delta > 0)
1318         {
1319           /* update old set by new delta */
1320           ai->value += delta;
1321         }
1322         else
1323         {
1324           /* update old set by new delta, but never go negative */
1325           if (ai->value < -delta)
1326             ai->value = 0;
1327           else
1328             ai->value += delta;
1329         }
1330       }
1331       else
1332       {
1333         /* new set overrides old set */
1334         ai->value = value;
1335       }
1336     }
1337     else
1338     {
1339       if (ACTION_UPDATE == type)
1340       {
1341         /* make delta cummulative */
1342         delta = (int64_t) value;
1343         ai->value += delta;
1344       }
1345       else
1346       {
1347         /* drop old 'update', use new 'set' instead */
1348         ai->value = value;
1349         ai->type = type;
1350       }
1351     }
1352     ai->timeout = GNUNET_TIME_relative_to_absolute (SET_TRANSMIT_TIMEOUT);
1353     ai->make_persistent = make_persistent;
1354     return;
1355   }
1356   /* no existing entry matches, create a fresh one */
1357   ai = GNUNET_new (struct GNUNET_STATISTICS_GetHandle);
1358   ai->sh = h;
1359   ai->subsystem = GNUNET_strdup (h->subsystem);
1360   ai->name = GNUNET_strdup (name);
1361   ai->timeout = GNUNET_TIME_relative_to_absolute (SET_TRANSMIT_TIMEOUT);
1362   ai->make_persistent = make_persistent;
1363   ai->msize = nsize;
1364   ai->value = value;
1365   ai->type = type;
1366   GNUNET_CONTAINER_DLL_insert_tail (h->action_head, h->action_tail,
1367                                     ai);
1368   schedule_action (h);
1369 }
1370
1371
1372 /**
1373  * Set statistic value for the peer.  Will always use our
1374  * subsystem (the argument used when "handle" was created).
1375  *
1376  * @param handle identification of the statistics service
1377  * @param name name of the statistic value
1378  * @param value new value to set
1379  * @param make_persistent should the value be kept across restarts?
1380  */
1381 void
1382 GNUNET_STATISTICS_set (struct GNUNET_STATISTICS_Handle *handle,
1383                        const char *name, uint64_t value, int make_persistent)
1384 {
1385   if (NULL == handle)
1386     return;
1387   GNUNET_assert (GNUNET_NO == handle->do_destroy);
1388   add_setter_action (handle, name, make_persistent, value, ACTION_SET);
1389 }
1390
1391
1392 /**
1393  * Set statistic value for the peer.  Will always use our
1394  * subsystem (the argument used when "handle" was created).
1395  *
1396  * @param handle identification of the statistics service
1397  * @param name name of the statistic value
1398  * @param delta change in value (added to existing value)
1399  * @param make_persistent should the value be kept across restarts?
1400  */
1401 void
1402 GNUNET_STATISTICS_update (struct GNUNET_STATISTICS_Handle *handle,
1403                           const char *name, int64_t delta, int make_persistent)
1404 {
1405   if (NULL == handle)
1406     return;
1407   if (0 == delta)
1408     return;
1409   GNUNET_assert (GNUNET_NO == handle->do_destroy);
1410   add_setter_action (handle, name, make_persistent, (uint64_t) delta,
1411                      ACTION_UPDATE);
1412 }
1413
1414
1415 /* end of statistics_api.c */