-removing 2nd argument from GNUNET_CLIENT_disconnect as it was virtually always GNUNE...
[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  * Reconnect at a later time, respecting back-off.
417  *
418  * @param h statistics handle
419  */
420 static void
421 reconnect_later (struct GNUNET_STATISTICS_Handle *h)
422 {
423   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == h->backoff_task);
424   if (h->do_destroy)
425   {
426     /* So we are shutting down and the service is not reachable.
427      * Chances are that it's down for good and we are not going to connect to
428      * it anymore.
429      * Give up and don't sync the rest of the data.
430      */
431     GNUNET_break (0);
432     h->do_destroy = GNUNET_NO;
433     GNUNET_STATISTICS_destroy (h, GNUNET_NO);
434     return;
435   }
436   h->backoff_task =
437     GNUNET_SCHEDULER_add_delayed (h->backoff, &reconnect_task, h);
438   h->backoff = GNUNET_TIME_relative_multiply (h->backoff, 2);
439   h->backoff =
440     GNUNET_TIME_relative_min (h->backoff, GNUNET_CONSTANTS_SERVICE_TIMEOUT);
441 }
442
443
444 /**
445  * Process a 'GNUNET_MESSAGE_TYPE_STATISTICS_VALUE' message.
446  *
447  * @param h statistics handle
448  * @param msg message received from the service, never NULL
449  * @return GNUNET_OK if the message was well-formed
450  */
451 static int
452 process_statistics_value_message (struct GNUNET_STATISTICS_Handle *h,
453                                   const struct GNUNET_MessageHeader *msg)
454 {
455   char *service;
456   char *name;
457   const struct GNUNET_STATISTICS_ReplyMessage *smsg;
458   uint16_t size;
459
460   if (h->current->aborted)
461   {
462     LOG (GNUNET_ERROR_TYPE_DEBUG, "Iteration was aborted, ignoring VALUE\n");
463     return GNUNET_OK;           /* don't bother */
464   }
465   size = ntohs (msg->size);
466   if (size < sizeof (struct GNUNET_STATISTICS_ReplyMessage))
467   {
468     GNUNET_break (0);
469     return GNUNET_SYSERR;
470   }
471   smsg = (const struct GNUNET_STATISTICS_ReplyMessage *) msg;
472   size -= sizeof (struct GNUNET_STATISTICS_ReplyMessage);
473   if (size !=
474       GNUNET_STRINGS_buffer_tokenize ((const char *) &smsg[1], size, 2,
475                                       &service, &name))
476   {
477     GNUNET_break (0);
478     return GNUNET_SYSERR;
479   }
480   LOG (GNUNET_ERROR_TYPE_DEBUG, "Received valid statistic on `%s:%s': %llu\n",
481        service, name, GNUNET_ntohll (smsg->value));
482   if (GNUNET_OK !=
483       h->current->proc (h->current->cls, service, name,
484                         GNUNET_ntohll (smsg->value),
485                         0 !=
486                         (ntohl (smsg->uid) & GNUNET_STATISTICS_PERSIST_BIT)))
487   {
488     LOG (GNUNET_ERROR_TYPE_DEBUG,
489          "Processing of remaining statistics aborted by client.\n");
490     h->current->aborted = GNUNET_YES;
491   }
492   LOG (GNUNET_ERROR_TYPE_DEBUG, "VALUE processed successfully\n");
493   return GNUNET_OK;
494 }
495
496
497 /**
498  * We have received a watch value from the service.  Process it.
499  *
500  * @param h statistics handle
501  * @param msg the watch value message
502  * @return GNUNET_OK if the message was well-formed, GNUNET_SYSERR if not,
503  *         GNUNET_NO if this watch has been cancelled
504  */
505 static int
506 process_watch_value (struct GNUNET_STATISTICS_Handle *h,
507                      const struct GNUNET_MessageHeader *msg)
508 {
509   const struct GNUNET_STATISTICS_WatchValueMessage *wvm;
510   struct GNUNET_STATISTICS_WatchEntry *w;
511   uint32_t wid;
512
513   if (sizeof (struct GNUNET_STATISTICS_WatchValueMessage) != ntohs (msg->size))
514   {
515     GNUNET_break (0);
516     return GNUNET_SYSERR;
517   }
518   wvm = (const struct GNUNET_STATISTICS_WatchValueMessage *) msg;
519   GNUNET_break (0 == ntohl (wvm->reserved));
520   wid = ntohl (wvm->wid);
521   if (wid >= h->watches_size)
522   {
523     GNUNET_break (0);
524     return GNUNET_SYSERR;
525   }
526   w = h->watches[wid];
527   if (NULL == w)  
528     return GNUNET_NO;  
529   (void) w->proc (w->proc_cls, w->subsystem, w->name,
530                   GNUNET_ntohll (wvm->value),
531                   0 != (ntohl (wvm->flags) & GNUNET_STATISTICS_PERSIST_BIT));
532   return GNUNET_OK;
533 }
534
535
536 /**
537  * Function called with messages from stats service.
538  *
539  * @param cls closure
540  * @param msg message received, NULL on timeout or fatal error
541  */
542 static void
543 receive_stats (void *cls, const struct GNUNET_MessageHeader *msg)
544 {
545   struct GNUNET_STATISTICS_Handle *h = cls;
546   struct GNUNET_STATISTICS_GetHandle *c;
547   int ret;
548
549   if (msg == NULL)
550   {
551     LOG (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
552          "Error receiving statistics from service, is the service running?\n");
553     do_disconnect (h);
554     reconnect_later (h);
555     return;
556   }
557   switch (ntohs (msg->type))
558   {
559   case GNUNET_MESSAGE_TYPE_STATISTICS_END:
560     LOG (GNUNET_ERROR_TYPE_DEBUG, "Received end of statistics marker\n");
561     if (NULL == (c = h->current))
562     {
563       GNUNET_break (0);
564       do_disconnect (h);
565       reconnect_later (h);
566       return;
567     }
568     h->backoff = GNUNET_TIME_UNIT_MILLISECONDS;
569     if (h->watches_size > 0)
570     {
571       GNUNET_CLIENT_receive (h->client, &receive_stats, h,
572                              GNUNET_TIME_UNIT_FOREVER_REL);
573     }
574     else
575     {
576       h->receiving = GNUNET_NO;
577     }    
578     h->current = NULL;
579     schedule_action (h);
580     if (c->cont != NULL)
581       c->cont (c->cls, GNUNET_OK);
582     free_action_item (c);
583     return;
584   case GNUNET_MESSAGE_TYPE_STATISTICS_VALUE:
585     if (GNUNET_OK != process_statistics_value_message (h, msg))
586     {
587       do_disconnect (h);
588       reconnect_later (h);
589       return;     
590     }
591     /* finally, look for more! */
592     LOG (GNUNET_ERROR_TYPE_DEBUG,
593          "Processing VALUE done, now reading more\n");
594     GNUNET_CLIENT_receive (h->client, &receive_stats, h,
595                            GNUNET_TIME_absolute_get_remaining (h->
596                                                                current->timeout));
597     h->backoff = GNUNET_TIME_UNIT_MILLISECONDS;
598     return;
599   case GNUNET_MESSAGE_TYPE_STATISTICS_WATCH_VALUE:
600     if (GNUNET_OK != 
601         (ret = process_watch_value (h, msg)))
602     {
603       do_disconnect (h);
604       if (GNUNET_NO == ret)
605         h->backoff = GNUNET_TIME_UNIT_MILLISECONDS; 
606       reconnect_later (h);
607       return;
608     }
609     h->backoff = GNUNET_TIME_UNIT_MILLISECONDS;
610     GNUNET_assert (h->watches_size > 0);
611     GNUNET_CLIENT_receive (h->client, &receive_stats, h,
612                            GNUNET_TIME_UNIT_FOREVER_REL);
613     return;    
614   default:
615     GNUNET_break (0);
616     do_disconnect (h);
617     reconnect_later (h);
618     return;
619   }
620 }
621
622
623 /**
624  * Transmit a GET request (and if successful, start to receive
625  * the response).
626  *
627  * @param handle statistics handle
628  * @param size how many bytes can we write to buf
629  * @param buf where to write requests to the service
630  * @return number of bytes written to buf
631  */
632 static size_t
633 transmit_get (struct GNUNET_STATISTICS_Handle *handle, size_t size, void *buf)
634 {
635   struct GNUNET_STATISTICS_GetHandle *c;
636   struct GNUNET_MessageHeader *hdr;
637   size_t slen1;
638   size_t slen2;
639   uint16_t msize;
640
641   GNUNET_assert (NULL != (c = handle->current));
642   if (buf == NULL)
643   {
644     /* timeout / error */
645     LOG (GNUNET_ERROR_TYPE_DEBUG,
646          "Transmission of request for statistics failed!\n");
647     do_disconnect (handle);
648     reconnect_later (handle);
649     return 0;
650   }
651   slen1 = strlen (c->subsystem) + 1;
652   slen2 = strlen (c->name) + 1;
653   msize = slen1 + slen2 + sizeof (struct GNUNET_MessageHeader);
654   GNUNET_assert (msize <= size);
655   hdr = (struct GNUNET_MessageHeader *) buf;
656   hdr->size = htons (msize);
657   hdr->type = htons (GNUNET_MESSAGE_TYPE_STATISTICS_GET);
658   GNUNET_assert (slen1 + slen2 ==
659                  GNUNET_STRINGS_buffer_fill ((char *) &hdr[1], slen1 + slen2, 2,
660                                              c->subsystem,
661                                              c->name));
662   if (GNUNET_YES != handle->receiving)
663   {
664     LOG (GNUNET_ERROR_TYPE_DEBUG,
665          "Transmission of GET done, now reading response\n");
666     handle->receiving = GNUNET_YES;
667     GNUNET_CLIENT_receive (handle->client, &receive_stats, handle,
668                            GNUNET_TIME_absolute_get_remaining (c->timeout));
669   }
670   return msize;
671 }
672
673
674 /**
675  * Transmit a WATCH request (and if successful, start to receive
676  * the response).
677  *
678  * @param handle statistics handle
679  * @param size how many bytes can we write to buf
680  * @param buf where to write requests to the service
681  * @return number of bytes written to buf
682  */
683 static size_t
684 transmit_watch (struct GNUNET_STATISTICS_Handle *handle, size_t size, void *buf)
685 {
686   struct GNUNET_MessageHeader *hdr;
687   size_t slen1;
688   size_t slen2;
689   uint16_t msize;
690
691   if (buf == NULL)
692   {
693     /* timeout / error */
694     LOG (GNUNET_ERROR_TYPE_DEBUG,
695          "Transmission of request for statistics failed!\n");
696     do_disconnect (handle);
697     reconnect_later (handle);
698     return 0;
699   }
700   LOG (GNUNET_ERROR_TYPE_DEBUG, "Transmitting watch request for `%s'\n",
701        handle->current->name);
702   slen1 = strlen (handle->current->subsystem) + 1;
703   slen2 = strlen (handle->current->name) + 1;
704   msize = slen1 + slen2 + sizeof (struct GNUNET_MessageHeader);
705   GNUNET_assert (msize <= size);
706   hdr = (struct GNUNET_MessageHeader *) buf;
707   hdr->size = htons (msize);
708   hdr->type = htons (GNUNET_MESSAGE_TYPE_STATISTICS_WATCH);
709   GNUNET_assert (slen1 + slen2 ==
710                  GNUNET_STRINGS_buffer_fill ((char *) &hdr[1], slen1 + slen2, 2,
711                                              handle->current->subsystem,
712                                              handle->current->name));
713   if (GNUNET_YES != handle->receiving)
714   {
715     handle->receiving = GNUNET_YES;
716     GNUNET_CLIENT_receive (handle->client, &receive_stats, handle,
717                            GNUNET_TIME_UNIT_FOREVER_REL);
718   }
719   GNUNET_assert (NULL == handle->current->cont);
720   free_action_item (handle->current);
721   handle->current = NULL;
722   return msize;
723 }
724
725
726 /**
727  * Transmit a SET/UPDATE request.
728  *
729  * @param handle statistics handle
730  * @param size how many bytes can we write to buf
731  * @param buf where to write requests to the service
732  * @return number of bytes written to buf
733  */
734 static size_t
735 transmit_set (struct GNUNET_STATISTICS_Handle *handle, size_t size, void *buf)
736 {
737   struct GNUNET_STATISTICS_SetMessage *r;
738   size_t slen;
739   size_t nlen;
740   size_t nsize;
741
742   if (NULL == buf)
743   {
744     do_disconnect (handle);
745     reconnect_later (handle);
746     return 0;
747   }
748   slen = strlen (handle->current->subsystem) + 1;
749   nlen = strlen (handle->current->name) + 1;
750   nsize = sizeof (struct GNUNET_STATISTICS_SetMessage) + slen + nlen;
751   if (size < nsize)
752   {
753     GNUNET_break (0);
754     do_disconnect (handle);
755     reconnect_later (handle);
756     return 0;
757   }
758   r = buf;
759   r->header.size = htons (nsize);
760   r->header.type = htons (GNUNET_MESSAGE_TYPE_STATISTICS_SET);
761   r->flags = 0;
762   r->value = GNUNET_htonll (handle->current->value);
763   if (handle->current->make_persistent)
764     r->flags |= htonl (GNUNET_STATISTICS_SETFLAG_PERSISTENT);
765   if (handle->current->type == ACTION_UPDATE)
766     r->flags |= htonl (GNUNET_STATISTICS_SETFLAG_RELATIVE);
767   GNUNET_assert (slen + nlen ==
768                  GNUNET_STRINGS_buffer_fill ((char *) &r[1], slen + nlen, 2,
769                                              handle->current->subsystem,
770                                              handle->current->name));
771   GNUNET_assert (NULL == handle->current->cont);
772   free_action_item (handle->current);
773   handle->current = NULL;
774   return nsize;
775 }
776
777
778 /**
779  * Function called when we are ready to transmit a request to the service.
780  *
781  * @param cls the 'struct GNUNET_STATISTICS_Handle'
782  * @param size how many bytes can we write to buf
783  * @param buf where to write requests to the service
784  * @return number of bytes written to buf
785  */
786 static size_t
787 transmit_action (void *cls, size_t size, void *buf)
788 {
789   struct GNUNET_STATISTICS_Handle *h = cls;
790   size_t ret;
791
792   h->th = NULL;
793   ret = 0;
794   if (NULL != h->current)
795     switch (h->current->type)
796     {
797     case ACTION_GET:
798       ret = transmit_get (h, size, buf);
799       break;
800     case ACTION_SET:
801     case ACTION_UPDATE:
802       ret = transmit_set (h, size, buf);
803       break;
804     case ACTION_WATCH:
805       ret = transmit_watch (h, size, buf);
806       break;
807     default:
808       GNUNET_assert (0);
809       break;
810     }
811   schedule_action (h);
812   return ret;
813 }
814
815
816 /**
817  * Get handle for the statistics service.
818  *
819  * @param subsystem name of subsystem using the service
820  * @param cfg services configuration in use
821  * @return handle to use
822  */
823 struct GNUNET_STATISTICS_Handle *
824 GNUNET_STATISTICS_create (const char *subsystem,
825                           const struct GNUNET_CONFIGURATION_Handle *cfg)
826 {
827   struct GNUNET_STATISTICS_Handle *ret;
828
829   GNUNET_assert (subsystem != NULL);
830   GNUNET_assert (cfg != NULL);
831   ret = GNUNET_malloc (sizeof (struct GNUNET_STATISTICS_Handle));
832   ret->cfg = cfg;
833   ret->subsystem = GNUNET_strdup (subsystem);
834   ret->backoff = GNUNET_TIME_UNIT_MILLISECONDS;
835   return ret;
836 }
837
838
839 /**
840  * Destroy a handle (free all state associated with
841  * it).
842  *
843  * @param h statistics handle to destroy
844  * @param sync_first set to GNUNET_YES if pending SET requests should
845  *        be completed
846  */
847 void
848 GNUNET_STATISTICS_destroy (struct GNUNET_STATISTICS_Handle *h, int sync_first)
849 {
850   struct GNUNET_STATISTICS_GetHandle *pos;
851   struct GNUNET_STATISTICS_GetHandle *next;
852   struct GNUNET_TIME_Relative timeout;
853   int i;
854
855   if (h == NULL)
856     return;
857   GNUNET_assert (GNUNET_NO == h->do_destroy); // Don't call twice.
858   if (GNUNET_SCHEDULER_NO_TASK != h->backoff_task)
859   {
860     GNUNET_SCHEDULER_cancel (h->backoff_task);
861     h->backoff_task = GNUNET_SCHEDULER_NO_TASK;
862   }
863   if (sync_first)
864   {
865     if (h->current != NULL)
866     {
867       if (h->current->type == ACTION_GET)
868       {
869         GNUNET_CLIENT_notify_transmit_ready_cancel (h->th);
870         h->th = NULL;
871         free_action_item (h->current);
872         h->current = NULL;
873       }
874     }
875     next = h->action_head; 
876     while (NULL != (pos = next))
877     {
878       next = pos->next;
879       if (pos->type == ACTION_GET)
880       {
881         GNUNET_CONTAINER_DLL_remove (h->action_head,
882                                      h->action_tail,
883                                      pos);
884         free_action_item (pos);
885       }
886     }
887     if ( (NULL == h->current) &&
888          (NULL != (h->current = h->action_head)) )
889       GNUNET_CONTAINER_DLL_remove (h->action_head,
890                                    h->action_tail,
891                                    h->current);
892     h->do_destroy = GNUNET_YES;
893     if ((h->current != NULL) && (h->th == NULL))
894     {
895       if (NULL == h->client)
896       {
897         /* instant-connect (regardless of back-off) to submit final value */
898         h->client = GNUNET_CLIENT_connect ("statistics", h->cfg);
899       }
900       if (NULL != h->client)
901       {
902         timeout = GNUNET_TIME_absolute_get_remaining (h->current->timeout);
903         h->th =
904           GNUNET_CLIENT_notify_transmit_ready (h->client, h->current->msize,
905                                                timeout, GNUNET_YES,
906                                                &transmit_action, h);
907         GNUNET_assert (NULL != h->th);
908       }
909     }
910     if (h->th != NULL)
911       return; /* do not finish destruction just yet */
912   }
913   while (NULL != (pos = h->action_head))
914   {
915     GNUNET_CONTAINER_DLL_remove (h->action_head,
916                                  h->action_tail,
917                                  pos);
918     free_action_item (pos);
919   }
920   do_disconnect (h);
921   for (i = 0; i < h->watches_size; i++)
922   {
923     if (NULL == h->watches[i])
924       continue; 
925     GNUNET_free (h->watches[i]->subsystem);
926     GNUNET_free (h->watches[i]->name);
927     GNUNET_free (h->watches[i]);
928   }
929   GNUNET_array_grow (h->watches, h->watches_size, 0);
930   GNUNET_free (h->subsystem);
931   GNUNET_free (h);
932 }
933
934
935 /**
936  * Schedule the next action to be performed.
937  *
938  * @param h statistics handle
939  */
940 static void
941 schedule_action (struct GNUNET_STATISTICS_Handle *h)
942 {
943   struct GNUNET_TIME_Relative timeout;
944
945   if ( (h->th != NULL) ||
946        (h->backoff_task != GNUNET_SCHEDULER_NO_TASK) )
947     return;                     /* action already pending */
948   if (GNUNET_YES != try_connect (h))
949   {
950     reconnect_later (h);
951     return;
952   }
953   if (NULL != h->current)
954     return; /* action already pending */
955   /* schedule next action */
956   h->current = h->action_head;
957   if (NULL == h->current)
958   {
959     if (h->do_destroy)
960     {
961       h->do_destroy = GNUNET_NO;
962       GNUNET_STATISTICS_destroy (h, GNUNET_YES);
963     }
964     return;
965   }
966   GNUNET_CONTAINER_DLL_remove (h->action_head, h->action_tail, h->current);
967   timeout = GNUNET_TIME_absolute_get_remaining (h->current->timeout);
968   if (NULL ==
969       (h->th =
970        GNUNET_CLIENT_notify_transmit_ready (h->client, h->current->msize,
971                                             timeout, GNUNET_YES,
972                                             &transmit_action, h)))
973   {
974     LOG (GNUNET_ERROR_TYPE_DEBUG,
975          "Failed to transmit request to statistics service.\n");
976     do_disconnect (h);
977     reconnect_later (h);
978   }
979 }
980
981
982 /**
983  * Get statistic from the peer.
984  *
985  * @param handle identification of the statistics service
986  * @param subsystem limit to the specified subsystem, NULL for our subsystem
987  * @param name name of the statistic value, NULL for all values
988  * @param timeout after how long should we give up (and call
989  *        cont with an error code)?
990  * @param cont continuation to call when done (can be NULL)
991  * @param proc function to call on each value
992  * @param cls closure for cont and proc
993  * @return NULL on error
994  */
995 struct GNUNET_STATISTICS_GetHandle *
996 GNUNET_STATISTICS_get (struct GNUNET_STATISTICS_Handle *handle,
997                        const char *subsystem, const char *name,
998                        struct GNUNET_TIME_Relative timeout,
999                        GNUNET_STATISTICS_Callback cont,
1000                        GNUNET_STATISTICS_Iterator proc, void *cls)
1001 {
1002   size_t slen1;
1003   size_t slen2;
1004   struct GNUNET_STATISTICS_GetHandle *ai;
1005
1006   if (NULL == handle)
1007     return NULL;
1008   GNUNET_assert (proc != NULL);
1009   GNUNET_assert (GNUNET_NO == handle->do_destroy);
1010   if (subsystem == NULL)
1011     subsystem = "";
1012   if (name == NULL)
1013     name = "";
1014   slen1 = strlen (subsystem) + 1;
1015   slen2 = strlen (name) + 1;
1016   GNUNET_assert (slen1 + slen2 + sizeof (struct GNUNET_MessageHeader) <
1017                  GNUNET_SERVER_MAX_MESSAGE_SIZE);
1018   ai = GNUNET_malloc (sizeof (struct GNUNET_STATISTICS_GetHandle));
1019   ai->sh = handle;
1020   ai->subsystem = GNUNET_strdup (subsystem);
1021   ai->name = GNUNET_strdup (name);
1022   ai->cont = cont;
1023   ai->proc = proc;
1024   ai->cls = cls;
1025   ai->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1026   ai->type = ACTION_GET;
1027   ai->msize = slen1 + slen2 + sizeof (struct GNUNET_MessageHeader);
1028   GNUNET_CONTAINER_DLL_insert_tail (handle->action_head, handle->action_tail,
1029                                     ai);
1030   schedule_action (handle);
1031   return ai;
1032 }
1033
1034
1035 /**
1036  * Cancel a 'get' request.  Must be called before the 'cont'
1037  * function is called.
1038  *
1039  * @param gh handle of the request to cancel
1040  */
1041 void
1042 GNUNET_STATISTICS_get_cancel (struct GNUNET_STATISTICS_GetHandle *gh)
1043 {
1044   if (NULL == gh)
1045     return;
1046   if (gh->sh->current == gh)
1047   {
1048     gh->aborted = GNUNET_YES;
1049   }
1050   else
1051   {
1052     GNUNET_CONTAINER_DLL_remove (gh->sh->action_head, gh->sh->action_tail, gh);
1053     GNUNET_free (gh->name);
1054     GNUNET_free (gh->subsystem);
1055     GNUNET_free (gh);
1056   }
1057 }
1058
1059
1060 /**
1061  * Watch statistics from the peer (be notified whenever they change).
1062  *
1063  * @param handle identification of the statistics service
1064  * @param subsystem limit to the specified subsystem, never NULL
1065  * @param name name of the statistic value, never NULL
1066  * @param proc function to call on each value
1067  * @param proc_cls closure for proc
1068  * @return GNUNET_OK on success, GNUNET_SYSERR on error
1069  */
1070 int
1071 GNUNET_STATISTICS_watch (struct GNUNET_STATISTICS_Handle *handle,
1072                          const char *subsystem, const char *name,
1073                          GNUNET_STATISTICS_Iterator proc, void *proc_cls)
1074 {
1075   struct GNUNET_STATISTICS_WatchEntry *w;
1076
1077   if (handle == NULL)
1078     return GNUNET_SYSERR;
1079   w = GNUNET_malloc (sizeof (struct GNUNET_STATISTICS_WatchEntry));
1080   w->subsystem = GNUNET_strdup (subsystem);
1081   w->name = GNUNET_strdup (name);
1082   w->proc = proc;
1083   w->proc_cls = proc_cls;
1084   GNUNET_array_append (handle->watches, handle->watches_size, w);
1085   schedule_watch_request (handle, w);
1086   return GNUNET_OK;
1087 }
1088
1089
1090 /**
1091  * Stop watching statistics from the peer.  
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 (no such watch)
1099  */
1100 int
1101 GNUNET_STATISTICS_watch_cancel (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   unsigned int i;
1107
1108   if (handle == NULL)
1109     return GNUNET_SYSERR;
1110   for (i=0;i<handle->watches_size;i++)
1111   {
1112     w = handle->watches[i];
1113     if ( (w->proc == proc) &&
1114          (w->proc_cls == proc_cls) &&
1115          (0 == strcmp (w->name, name)) &&
1116          (0 == strcmp (w->subsystem, subsystem)) )
1117     {
1118       GNUNET_free (w->name);
1119       GNUNET_free (w->subsystem);
1120       GNUNET_free (w);
1121       handle->watches[i] = NULL;      
1122       return GNUNET_OK;
1123     }    
1124   }
1125   return GNUNET_SYSERR;
1126 }
1127
1128
1129
1130 /**
1131  * Queue a request to change a statistic.
1132  *
1133  * @param h statistics handle
1134  * @param name name of the value
1135  * @param make_persistent  should the value be kept across restarts?
1136  * @param value new value or change
1137  * @param type type of the action (ACTION_SET or ACTION_UPDATE)
1138  */
1139 static void
1140 add_setter_action (struct GNUNET_STATISTICS_Handle *h, const char *name,
1141                    int make_persistent, uint64_t value, enum ActionType type)
1142 {
1143   struct GNUNET_STATISTICS_GetHandle *ai;
1144   size_t slen;
1145   size_t nlen;
1146   size_t nsize;
1147   int64_t delta;
1148
1149   GNUNET_assert (h != NULL);
1150   GNUNET_assert (name != NULL);
1151   slen = strlen (h->subsystem) + 1;
1152   nlen = strlen (name) + 1;
1153   nsize = sizeof (struct GNUNET_STATISTICS_SetMessage) + slen + nlen;
1154   if (nsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1155   {
1156     GNUNET_break (0);
1157     return;
1158   }
1159   for (ai = h->action_head; ai != NULL; ai = ai->next)
1160   {
1161     if (! ( (0 == strcmp (ai->subsystem, h->subsystem)) &&
1162             (0 == strcmp (ai->name, name)) && 
1163             ( (ai->type == ACTION_UPDATE) ||
1164               (ai->type == ACTION_SET) ) ) )
1165       continue;
1166     if (ai->type == ACTION_SET)
1167     {
1168       if (type == ACTION_UPDATE)
1169       {
1170         delta = (int64_t) value;
1171         if (delta > 0)
1172         {
1173           /* update old set by new delta */
1174           ai->value += delta;
1175         }
1176         else
1177         {
1178           /* update old set by new delta, but never go negative */
1179           if (ai->value < -delta)
1180             ai->value = 0;
1181           else
1182             ai->value += delta;
1183         }
1184       }
1185       else
1186       {
1187         /* new set overrides old set */
1188         ai->value = value;
1189       }
1190     }
1191     else
1192     {
1193       if (type == ACTION_UPDATE)
1194       {
1195         /* make delta cummulative */
1196         delta = (int64_t) value;
1197         ai->value += delta;
1198       }
1199       else
1200       {
1201         /* drop old 'update', use new 'set' instead */
1202         ai->value = value;
1203         ai->type = type;
1204       }
1205     }
1206     ai->timeout = GNUNET_TIME_relative_to_absolute (SET_TRANSMIT_TIMEOUT);
1207     ai->make_persistent = make_persistent;
1208     return;  
1209   }
1210   /* no existing entry matches, create a fresh one */
1211   ai = GNUNET_malloc (sizeof (struct GNUNET_STATISTICS_GetHandle));
1212   ai->sh = h;
1213   ai->subsystem = GNUNET_strdup (h->subsystem);
1214   ai->name = GNUNET_strdup (name);
1215   ai->timeout = GNUNET_TIME_relative_to_absolute (SET_TRANSMIT_TIMEOUT);
1216   ai->make_persistent = make_persistent;
1217   ai->msize = nsize;
1218   ai->value = value;
1219   ai->type = type;
1220   GNUNET_CONTAINER_DLL_insert_tail (h->action_head, h->action_tail,
1221                                     ai);
1222   schedule_action (h);
1223 }
1224
1225
1226 /**
1227  * Set statistic value for the peer.  Will always use our
1228  * subsystem (the argument used when "handle" was created).
1229  *
1230  * @param handle identification of the statistics service
1231  * @param name name of the statistic value
1232  * @param value new value to set
1233  * @param make_persistent should the value be kept across restarts?
1234  */
1235 void
1236 GNUNET_STATISTICS_set (struct GNUNET_STATISTICS_Handle *handle,
1237                        const char *name, uint64_t value, int make_persistent)
1238 {
1239   if (handle == NULL)
1240     return;
1241   GNUNET_assert (GNUNET_NO == handle->do_destroy);
1242   add_setter_action (handle, name, make_persistent, value, ACTION_SET);
1243 }
1244
1245
1246 /**
1247  * Set statistic value for the peer.  Will always use our
1248  * subsystem (the argument used when "handle" was created).
1249  *
1250  * @param handle identification of the statistics service
1251  * @param name name of the statistic value
1252  * @param delta change in value (added to existing value)
1253  * @param make_persistent should the value be kept across restarts?
1254  */
1255 void
1256 GNUNET_STATISTICS_update (struct GNUNET_STATISTICS_Handle *handle,
1257                           const char *name, int64_t delta, int make_persistent)
1258 {
1259   if (handle == NULL)
1260     return;
1261   if (delta == 0)
1262     return;
1263   GNUNET_assert (GNUNET_NO == handle->do_destroy);
1264   add_setter_action (handle, name, make_persistent, (uint64_t) delta,
1265                      ACTION_UPDATE);
1266 }
1267
1268
1269 /* end of statistics_api.c */