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