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