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