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