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