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