convert statistics service to new service MQ API
[oweals/gnunet.git] / src / statistics / gnunet-service-statistics.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2009, 2010, 2012, 2014, 2016 GNUnet e.V.
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 3, 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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20
21 /**
22  * @file statistics/gnunet-service-statistics.c
23  * @brief program that tracks statistics
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet_bio_lib.h"
28 #include "gnunet_container_lib.h"
29 #include "gnunet_disk_lib.h"
30 #include "gnunet_getopt_lib.h"
31 #include "gnunet_protocols.h"
32 #include "gnunet_service_lib.h"
33 #include "gnunet_statistics_service.h"
34 #include "gnunet_strings_lib.h"
35 #include "gnunet_time_lib.h"
36 #include "statistics.h"
37
38 /**
39  * Watch entry.
40  */
41 struct WatchEntry
42 {
43
44   /**
45    * Watch entries are kept in a linked list.
46    */
47   struct WatchEntry *next;
48
49   /**
50    * Watch entries are kept in a linked list.
51    */
52   struct WatchEntry *prev;
53
54   /**
55    * For which client is this watch entry?
56    */
57   struct ClientEntry *ce;
58
59   /**
60    * Last value we communicated to the client for this watch entry.
61    */
62   uint64_t last_value;
63
64   /**
65    * Unique watch number for this client and this watched value.
66    */
67   uint32_t wid;
68
69   /**
70    * Is last_value valid
71    * #GNUNET_NO : last_value is n/a, #GNUNET_YES: last_value is valid
72    */
73   int last_value_set;
74
75 };
76
77
78 /**
79  * We keep the statistics organized by subsystem for faster
80  * lookup during SET operations.
81  */
82 struct SubsystemEntry;
83
84
85 /**
86  * Entry in the statistics list.
87  */
88 struct StatsEntry
89 {
90   /**
91    * This is a linked list.
92    */
93   struct StatsEntry *next;
94
95   /**
96    * This is a linked list.
97    */
98   struct StatsEntry *prev;
99
100   /**
101    * Subsystem this entry belongs to.
102    */
103   struct SubsystemEntry *subsystem;
104
105   /**
106    * Name for the value stored by this entry, allocated at the end of
107    * this struct.
108    */
109   const char *name;
110
111   /**
112    * Watch context for changes to this value, or NULL for none.
113    */
114   struct WatchEntry *we_head;
115
116   /**
117    * Watch context for changes to this value, or NULL for none.
118    */
119   struct WatchEntry *we_tail;
120
121   /**
122    * Our value.
123    */
124   uint64_t value;
125
126   /**
127    * Unique ID.
128    */
129   uint32_t uid;
130
131   /**
132    * Is this value persistent?
133    */
134   int persistent;
135
136   /**
137    * Is this value set?
138    * #GNUNET_NO: value is n/a, #GNUNET_YES: value is valid
139    */
140   int set;
141
142 };
143
144
145 /**
146  * We keep the statistics organized by subsystem for faster
147  * lookup during SET operations.
148  */
149 struct SubsystemEntry
150 {
151   /**
152    * Subsystems are kept in a DLL.
153    */
154   struct SubsystemEntry *next;
155
156   /**
157    * Subsystems are kept in a DLL.
158    */
159   struct SubsystemEntry *prev;
160
161   /**
162    * Head of list of values kept for this subsystem.
163    */
164   struct StatsEntry *stat_head;
165
166   /**
167    * Tail of list of values kept for this subsystem.
168    */
169   struct StatsEntry *stat_tail;
170
171   /**
172    * Name of the subsystem this entry is for, allocated at
173    * the end of this struct, do not free().
174    */
175   const char *service;
176
177 };
178
179
180 /**
181  * Client entry.
182  */
183 struct ClientEntry
184 {
185   /**
186    * Corresponding server handle.
187    */
188   struct GNUNET_SERVICE_Client *client;
189
190   /**
191    * Corresponding message queue.
192    */
193   struct GNUNET_MQ_Handle *mq;
194
195   /**
196    * Which subsystem is this client writing to (SET/UPDATE)?
197    */
198   struct SubsystemEntry *subsystem;
199
200   /**
201    * Maximum watch ID used by this client so far.
202    */
203   uint32_t max_wid;
204
205 };
206
207
208 /**
209  * Our configuration.
210  */
211 static const struct GNUNET_CONFIGURATION_Handle *cfg;
212
213 /**
214  * Head of linked list of subsystems with active statistics.
215  */
216 static struct SubsystemEntry *sub_head;
217
218 /**
219  * Tail of linked list of subsystems with active statistics.
220  */
221 static struct SubsystemEntry *sub_tail;
222
223 /**
224  * Number of connected clients.
225  */
226 static unsigned int client_count;
227
228 /**
229  * Our notification context.
230  */
231 static struct GNUNET_NotificationContext *nc;
232
233 /**
234  * Counter used to generate unique values.
235  */
236 static uint32_t uidgen;
237
238 /**
239  * Set to #GNUNET_YES if we are shutting down as soon as possible.
240  */
241 static int in_shutdown;
242
243
244 /**
245  * Write persistent statistics to disk.
246  */
247 static void
248 save ()
249 {
250   struct SubsystemEntry *se;
251   struct StatsEntry *pos;
252   char *fn;
253   struct GNUNET_BIO_WriteHandle *wh;
254   uint16_t size;
255   unsigned long long total;
256   size_t nlen;
257   size_t slen;
258   struct GNUNET_STATISTICS_SetMessage *msg;
259
260   if (GNUNET_OK !=
261       GNUNET_CONFIGURATION_get_value_filename (cfg,
262                                                "STATISTICS",
263                                                "DATABASE",
264                                                &fn))
265   {
266     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
267                                "STATISTICS",
268                                "DATABASE");
269     return;
270   }
271   (void) GNUNET_DISK_directory_create_for_file (fn);
272   wh = GNUNET_BIO_write_open (fn);
273   total = 0;
274   while (NULL != (se = sub_head))
275   {
276     GNUNET_CONTAINER_DLL_remove (sub_head,
277                                  sub_tail,
278                                  se);
279     slen = strlen (se->service) + 1;
280     while (NULL != (pos = se->stat_head))
281     {
282       GNUNET_CONTAINER_DLL_remove (se->stat_head,
283                                    se->stat_tail,
284                                    pos);
285       if ( (pos->persistent) &&
286            (NULL != wh) )
287       {
288         nlen = strlen (pos->name) + 1;
289         size = sizeof (struct GNUNET_STATISTICS_SetMessage) + nlen + slen;
290         GNUNET_assert (size < UINT16_MAX);
291         msg = GNUNET_malloc (size);
292
293         msg->header.size = htons ((uint16_t) size);
294         msg->header.type = htons (GNUNET_MESSAGE_TYPE_STATISTICS_SET);
295         GNUNET_assert (nlen + slen ==
296                        GNUNET_STRINGS_buffer_fill ((char *) &msg[1],
297                                                    nlen + slen,
298                                                    2,
299                                                    se->service,
300                                                    pos->name));
301         msg->flags = htonl (pos->persistent ? GNUNET_STATISTICS_SETFLAG_PERSISTENT : 0);
302         msg->value = GNUNET_htonll (pos->value);
303         if (GNUNET_OK != GNUNET_BIO_write (wh,
304                                            msg,
305                                            size))
306         {
307           GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
308                                     "write",
309                                     fn);
310           if (GNUNET_OK != GNUNET_BIO_write_close (wh))
311             GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
312                                       "close",
313                                       fn);
314           wh = NULL;
315         }
316         else
317         {
318           total += size;
319         }
320         GNUNET_free (msg);
321       }
322       GNUNET_free (pos);
323     }
324     GNUNET_free (se);
325   }
326   if (NULL != wh)
327   {
328     if (GNUNET_OK !=
329         GNUNET_BIO_write_close (wh))
330       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
331                                 "close",
332                                 fn);
333     if (0 == total)
334       GNUNET_break (0 ==
335                     UNLINK (fn));
336     else
337       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
338                   _("Wrote %llu bytes of statistics to `%s'\n"),
339                   total,
340                   fn);
341   }
342   GNUNET_free_non_null (fn);
343 }
344
345
346 /**
347  * Transmit the given stats value.
348  *
349  * @param client receiver of the value
350  * @param e value to transmit
351  */
352 static void
353 transmit (struct ClientEntry *ce,
354           const struct StatsEntry *e)
355 {
356   struct GNUNET_MQ_Envelope *env;
357   struct GNUNET_STATISTICS_ReplyMessage *m;
358   size_t size;
359
360   size = strlen (e->subsystem->service) + 1 +
361     strlen (e->name) + 1;
362   GNUNET_assert (size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
363   env = GNUNET_MQ_msg_extra (m,
364                              size,
365                              GNUNET_MESSAGE_TYPE_STATISTICS_VALUE);
366   m->uid = htonl (e->uid);
367   if (e->persistent)
368     m->uid |= htonl (GNUNET_STATISTICS_PERSIST_BIT);
369   m->value = GNUNET_htonll (e->value);
370   GNUNET_assert (size ==
371                  GNUNET_STRINGS_buffer_fill ((char *) &m[1],
372                                              size,
373                                              2,
374                                              e->subsystem->service,
375                                              e->name));
376   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
377               "Transmitting value for `%s:%s' (%d): %llu\n",
378               e->subsystem->service,
379               e->name,
380               e->persistent,
381               (unsigned long long) e->value);
382   GNUNET_MQ_send (ce->mq,
383                   env);
384 }
385
386
387 /**
388  * Callback called when a client connects to the service.
389  *
390  * @param cls closure for the service
391  * @param c the new client that connected to the service
392  * @param mq the message queue used to send messages to the client
393  * @return @a c
394  */
395 static void *
396 client_connect_cb (void *cls,
397                    struct GNUNET_SERVICE_Client *c,
398                    struct GNUNET_MQ_Handle *mq)
399 {
400   struct ClientEntry *ce;
401
402   ce = GNUNET_new (struct ClientEntry);
403   ce->client = c;
404   ce->mq = mq;
405   client_count++;
406   GNUNET_notification_context_add (nc,
407                                    mq);
408   return ce;
409 }
410
411
412 /**
413  * Check integrity of GET-message.
414  *
415  * @param cls identification of the client
416  * @param message the actual message
417  * @return #GNUNET_OK if @a message is well-formed
418  */
419 static int
420 check_get (void *cls,
421            const struct GNUNET_MessageHeader *message)
422 {
423   const char *service;
424   const char *name;
425   size_t size;
426
427   size = ntohs (message->size) - sizeof (struct GNUNET_MessageHeader);
428   if (size !=
429       GNUNET_STRINGS_buffer_tokenize ((const char *) &message[1],
430                                       size,
431                                       2,
432                                       &service,
433                                       &name))
434   {
435     GNUNET_break (0);
436     return GNUNET_SYSERR;
437   }
438   return GNUNET_OK;
439 }
440
441
442 /**
443  * Handle GET-message.
444  *
445  * @param cls identification of the client
446  * @param message the actual message
447  */
448 static void
449 handle_get (void *cls,
450             const struct GNUNET_MessageHeader *message)
451 {
452   struct ClientEntry *ce = cls;
453   struct GNUNET_MQ_Envelope *env;
454   struct GNUNET_MessageHeader *end;
455   const char *service;
456   const char *name;
457   size_t slen;
458   size_t nlen;
459   struct SubsystemEntry *se;
460   struct StatsEntry *pos;
461   size_t size;
462
463   size = ntohs (message->size) - sizeof (struct GNUNET_MessageHeader);
464   GNUNET_assert (size ==
465                  GNUNET_STRINGS_buffer_tokenize ((const char *) &message[1],
466                                                  size,
467                                                  2,
468                                                  &service,
469                                                  &name));
470   slen = strlen (service);
471   nlen = strlen (name);
472   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
473               "Received request for statistics on `%s:%s'\n",
474               slen ? service : "*",
475               nlen ? name : "*");
476   for (se = sub_head; NULL != se; se = se->next)
477   {
478     if (! ( (0 == slen) ||
479             (0 == strcmp (service, se->service))) )
480       continue;
481     for (pos = se->stat_head; NULL != pos; pos = pos->next)
482     {
483       if  (! ( (0 == nlen) ||
484                (0 == strcmp (name,
485                              pos->name))) )
486         continue;
487       transmit (ce,
488                 pos);
489     }
490   }
491   env = GNUNET_MQ_msg (end,
492                        GNUNET_MESSAGE_TYPE_STATISTICS_END);
493   GNUNET_MQ_send (ce->mq,
494                   env);
495   GNUNET_SERVICE_client_continue (ce->client);
496 }
497
498
499 /**
500  * Notify all clients listening about a change to a value.
501  *
502  * @param se value that changed
503  */
504 static void
505 notify_change (struct StatsEntry *se)
506 {
507   struct GNUNET_MQ_Envelope *env;
508   struct GNUNET_STATISTICS_WatchValueMessage *wvm;
509   struct WatchEntry *pos;
510
511   for (pos = se->we_head; NULL != pos; pos = pos->next)
512   {
513     if (GNUNET_YES == pos->last_value_set)
514     {
515       if (pos->last_value == se->value)
516         continue;
517     }
518     else
519     {
520       pos->last_value_set = GNUNET_YES;
521     }
522     env = GNUNET_MQ_msg (wvm,
523                          GNUNET_MESSAGE_TYPE_STATISTICS_WATCH_VALUE);
524     wvm->flags = htonl (se->persistent ? GNUNET_STATISTICS_SETFLAG_PERSISTENT : 0);
525     wvm->wid = htonl (pos->wid);
526     wvm->reserved = htonl (0);
527     wvm->value = GNUNET_htonll (se->value);
528     GNUNET_MQ_send (pos->ce->mq,
529                     env);
530     pos->last_value = se->value;
531   }
532 }
533
534
535 /**
536  * Find the subsystem entry of the given name for the specified client.
537  *
538  * @param ce client looking for the subsystem, may contain a hint
539  *           to find the entry faster, can be NULL
540  * @param service name of the subsystem to look for
541  * @return subsystem entry, never NULL (subsystem entry is created if necessary)
542  */
543 static struct SubsystemEntry *
544 find_subsystem_entry (struct ClientEntry *ce,
545                       const char *service)
546 {
547   size_t slen;
548   struct SubsystemEntry *se;
549
550   if (NULL != ce)
551     se = ce->subsystem;
552   else
553     se = NULL;
554   if ( (NULL == se) ||
555        (0 != strcmp (service,
556                      se->service)) )
557   {
558     for (se = sub_head; NULL != se; se = se->next)
559       if (0 == strcmp (service,
560                        se->service))
561         break;
562     if (NULL != ce)
563       ce->subsystem = se;
564   }
565   if (NULL != se)
566     return se;
567   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
568               "Allocating new subsystem entry `%s'\n",
569               service);
570   slen = strlen (service) + 1;
571   se = GNUNET_malloc (sizeof (struct SubsystemEntry) +
572                       slen);
573   GNUNET_memcpy (&se[1],
574           service,
575           slen);
576   se->service = (const char *) &se[1];
577   GNUNET_CONTAINER_DLL_insert (sub_head,
578                                sub_tail,
579                                se);
580   if (NULL != ce)
581     ce->subsystem = se;
582   return se;
583 }
584
585
586 /**
587  * Find the statistics entry of the given subsystem.
588  *
589  * @param subsystem subsystem to look in
590  * @param name name of the entry to look for
591  * @return statistis entry, or NULL if not found
592  */
593 static struct StatsEntry *
594 find_stat_entry (struct SubsystemEntry *se,
595                  const char *name)
596 {
597   struct StatsEntry *pos;
598
599   for (pos = se->stat_head; NULL != pos; pos = pos->next)
600     if  (0 == strcmp (name, pos->name))
601       return pos;
602   return NULL;
603 }
604
605
606 /**
607  * Check format of SET-message.
608  *
609  * @param cls the `struct ClientEntry`
610  * @param message the actual message
611  * @return #GNUNET_OK if message is well-formed
612  */
613 static int
614 check_set (void *cls,
615            const struct GNUNET_STATISTICS_SetMessage *msg)
616 {
617   const char *service;
618   const char *name;
619   size_t msize;
620
621   msize = ntohs (msg->header.size) - sizeof (*msg);
622   if (msize !=
623       GNUNET_STRINGS_buffer_tokenize ((const char *) &msg[1],
624                                       msize,
625                                       2,
626                                       &service,
627                                       &name))
628   {
629     GNUNET_break (0);
630     return GNUNET_SYSERR;
631   }
632   return GNUNET_OK;
633 }
634
635
636 /**
637  * Handle SET-message.
638  *
639  * @param cls the `struct ClientEntry`
640  * @param message the actual message
641  */
642 static void
643 handle_set (void *cls,
644             const struct GNUNET_STATISTICS_SetMessage *msg)
645 {
646   struct ClientEntry *ce = cls;
647   const char *service;
648   const char *name;
649   size_t nlen;
650   uint16_t msize;
651   uint16_t size;
652   struct SubsystemEntry *se;
653   struct StatsEntry *pos;
654   uint32_t flags;
655   uint64_t value;
656   int64_t delta;
657   int changed;
658   int initial_set;
659
660   msize = ntohs (msg->header.size);
661   size = msize - sizeof (struct GNUNET_STATISTICS_SetMessage);
662   GNUNET_assert (size ==
663                  GNUNET_STRINGS_buffer_tokenize ((const char *) &msg[1],
664                                                  size,
665                                                  2,
666                                                  &service,
667                                                  &name));
668   se = find_subsystem_entry (ce,
669                              service);
670   flags = ntohl (msg->flags);
671   value = GNUNET_ntohll (msg->value);
672   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
673               "Received request to update statistic on `%s:%s' (%u) to/by %llu\n",
674               service,
675               name,
676               (unsigned int) flags,
677               (unsigned long long) value);
678   pos = find_stat_entry (se,
679                          name);
680   if (NULL != pos)
681   {
682     initial_set = 0;
683     if (0 == (flags & GNUNET_STATISTICS_SETFLAG_RELATIVE))
684     {
685       changed = (pos->value != value);
686       pos->value = value;
687     }
688     else
689     {
690       delta = (int64_t) value;
691       if ((delta < 0) && (pos->value < -delta))
692       {
693         changed = (0 != pos->value);
694         pos->value = 0;
695       }
696       else
697       {
698         changed = (0 != delta);
699         GNUNET_break ( (delta <= 0) ||
700                        (pos->value + delta > pos->value) );
701         pos->value += delta;
702       }
703     }
704     if (GNUNET_NO == pos->set)
705     {
706       pos->set = GNUNET_YES;
707       initial_set = 1;
708     }
709     pos->persistent = (0 != (flags & GNUNET_STATISTICS_SETFLAG_PERSISTENT));
710     if (pos != se->stat_head)
711     {
712       /* move to front for faster setting next time! */
713       GNUNET_CONTAINER_DLL_remove (se->stat_head,
714                                    se->stat_tail,
715                                    pos);
716       GNUNET_CONTAINER_DLL_insert (se->stat_head,
717                                    se->stat_tail,
718                                    pos);
719     }
720     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
721                 "Statistic `%s:%s' updated to value %llu (%d).\n",
722                 service,
723                 name,
724                 (unsigned long long) pos->value,
725                 pos->persistent);
726     if ( (changed) ||
727          (1 == initial_set) )
728       notify_change (pos);
729     GNUNET_SERVICE_client_continue (ce->client);
730     return;
731   }
732   /* not found, create a new entry */
733   nlen = strlen (name) + 1;
734   pos = GNUNET_malloc (sizeof (struct StatsEntry) + nlen);
735   GNUNET_memcpy (&pos[1],
736                  name,
737                  nlen);
738   pos->name = (const char *) &pos[1];
739   pos->subsystem = se;
740   if ( (0 == (flags & GNUNET_STATISTICS_SETFLAG_RELATIVE)) ||
741        (0 < (int64_t) GNUNET_ntohll (msg->value)) )
742   {
743     pos->value = GNUNET_ntohll (msg->value);
744     pos->set = GNUNET_YES;
745   }
746   else
747   {
748     pos->set = GNUNET_NO;
749   }
750   pos->uid = uidgen++;
751   pos->persistent = (0 != (flags & GNUNET_STATISTICS_SETFLAG_PERSISTENT));
752   GNUNET_CONTAINER_DLL_insert (se->stat_head,
753                                se->stat_tail,
754                                pos);
755   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
756               "New statistic on `%s:%s' with value %llu created.\n",
757               service,
758               name,
759               (unsigned long long) pos->value);
760   if (NULL != ce)
761     GNUNET_SERVICE_client_continue (ce->client);
762 }
763
764
765 /**
766  * Check integrity of WATCH-message.
767  *
768  * @param cls the `struct ClientEntry *`
769  * @param message the actual message
770  * @return #GNUNET_OK if message is well-formed
771  */
772 static int
773 check_watch (void *cls,
774              const struct GNUNET_MessageHeader *message)
775 {
776   size_t size;
777   const char *service;
778   const char *name;
779   
780   size = ntohs (message->size) - sizeof (struct GNUNET_MessageHeader);
781   if (size !=
782       GNUNET_STRINGS_buffer_tokenize ((const char *) &message[1],
783                                       size,
784                                       2,
785                                       &service,
786                                       &name))
787   {
788     GNUNET_break (0);
789     return GNUNET_SYSERR;
790   }
791   return GNUNET_OK;
792 }
793
794
795 /**
796  * Handle WATCH-message.
797  *
798  * @param cls the `struct ClientEntry *`
799  * @param message the actual message
800  */
801 static void
802 handle_watch (void *cls,
803               const struct GNUNET_MessageHeader *message)
804 {
805   struct ClientEntry *ce = cls;
806   const char *service;
807   const char *name;
808   uint16_t msize;
809   uint16_t size;
810   struct SubsystemEntry *se;
811   struct StatsEntry *pos;
812   struct WatchEntry *we;
813   size_t nlen;
814
815   if (NULL == nc)
816   {
817     GNUNET_SERVICE_client_drop (ce->client);
818     return;
819   }
820   GNUNET_SERVICE_client_mark_monitor (ce->client);
821   msize = ntohs (message->size);
822   size = msize - sizeof (struct GNUNET_MessageHeader);
823   GNUNET_assert (size ==
824                  GNUNET_STRINGS_buffer_tokenize ((const char *) &message[1],
825                                                  size,
826                                                  2,
827                                                  &service,
828                                                  &name));
829   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
830               "Received request to watch statistic on `%s:%s'\n",
831               service,
832               name);
833   se = find_subsystem_entry (ce,
834                              service);
835   pos = find_stat_entry (se,
836                          name);
837   if (NULL == pos)
838   {
839     nlen = strlen (name) + 1;
840     pos = GNUNET_malloc (sizeof (struct StatsEntry) +
841                          nlen);
842     GNUNET_memcpy (&pos[1],
843                    name,
844                    nlen);
845     pos->name = (const char *) &pos[1];
846     pos->subsystem = se;
847     GNUNET_CONTAINER_DLL_insert (se->stat_head,
848                                  se->stat_tail,
849                                  pos);
850     pos->uid = uidgen++;
851     pos->set = GNUNET_NO;
852     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
853                 "New statistic on `%s:%s' with value %llu created.\n",
854                 service,
855                 name,
856                 (unsigned long long) pos->value);
857   }
858   we = GNUNET_new (struct WatchEntry);
859   we->ce = ce;
860   we->last_value_set = GNUNET_NO;
861   we->wid = ce->max_wid++;
862   GNUNET_CONTAINER_DLL_insert (pos->we_head,
863                                pos->we_tail,
864                                we);
865   if (0 != pos->value)
866     notify_change (pos);
867   GNUNET_SERVICE_client_continue (ce->client);
868 }
869
870
871 /**
872  * Handle DISCONNECT-message.  Sync to disk and send
873  * back a #GNUNET_MESSAGE_TYPE_STATISTICS_DISCONNECT_CONFIRM 
874  * message.
875  *
876  * @param cls the `struct ClientEntry *`
877  * @param message the actual message
878  */
879 static void
880 handle_disconnect (void *cls,
881                    const struct GNUNET_MessageHeader *message)
882 {
883   struct ClientEntry *ce = cls;
884   struct GNUNET_MQ_Envelope *env;
885   struct GNUNET_MessageHeader *msg;
886
887   env = GNUNET_MQ_msg (msg,
888                        GNUNET_MESSAGE_TYPE_STATISTICS_DISCONNECT_CONFIRM);
889   GNUNET_MQ_send (ce->mq,
890                   env);
891   GNUNET_SERVICE_client_continue (ce->client);
892 }
893
894
895 /**
896  * Actually perform the shutdown.
897  */
898 static void
899 do_shutdown ()
900 {
901   struct WatchEntry *we;
902   struct StatsEntry *pos;
903   struct SubsystemEntry *se;
904
905   if (NULL == nc)
906     return;
907   save ();
908   GNUNET_notification_context_destroy (nc);
909   nc = NULL;
910   GNUNET_assert (0 == client_count);
911   while (NULL != (se = sub_head))
912   {
913     GNUNET_CONTAINER_DLL_remove (sub_head,
914                                  sub_tail,
915                                  se);
916     while (NULL != (pos = se->stat_head))
917     {
918       GNUNET_CONTAINER_DLL_remove (se->stat_head,
919                                    se->stat_tail,
920                                    pos);
921       while (NULL != (we = pos->we_head))
922       {
923         GNUNET_break (0);
924         GNUNET_CONTAINER_DLL_remove (pos->we_head,
925                                      pos->we_tail,
926                                      we);
927         GNUNET_free (we);
928       }
929       GNUNET_free (pos);
930     }
931     GNUNET_free (se);
932   }
933 }
934
935
936 /**
937  * Task run during shutdown.
938  *
939  * @param cls unused
940  */
941 static void
942 shutdown_task (void *cls)
943 {
944   in_shutdown = GNUNET_YES;
945   if (0 != client_count)
946     return;
947   do_shutdown ();
948 }
949
950
951 /**
952  * A client disconnected.  Remove all of its data structure entries.
953  *
954  * @param cls closure, NULL
955  * @param client identification of the client
956  * @param app_cls the `struct ClientEntry *`
957  */
958 static void
959 client_disconnect_cb (void *cls,
960                       struct GNUNET_SERVICE_Client *client,
961                       void *app_cls)
962 {
963   struct ClientEntry *ce = app_cls;
964   struct WatchEntry *we;
965   struct WatchEntry *wen;
966   struct StatsEntry *pos;
967   struct SubsystemEntry *se;
968
969   client_count--;
970   for (se = sub_head; NULL != se; se = se->next)
971   {
972     for (pos = se->stat_head; NULL != pos; pos = pos->next)
973     {
974       wen = pos->we_head;
975       while (NULL != (we = wen))
976       {
977         wen = we->next;
978         if (we->ce != ce)
979           continue;
980         GNUNET_CONTAINER_DLL_remove (pos->we_head,
981                                      pos->we_tail,
982                                      we);
983         GNUNET_free (we);
984       }
985     }
986   }
987   if ( (0 == client_count) &&
988        (GNUNET_YES == in_shutdown) )
989     do_shutdown ();
990 }
991
992
993 /**
994  * We've read a `struct GNUNET_STATISTICS_SetMessage *` from
995  * disk. Check that it is well-formed, and if so pass it to 
996  * the handler for set messages.
997  *
998  * @param cls NULL
999  * @param message the message found on disk
1000  * @return #GNUNET_OK on success, #GNUNET_SYSERR to stop further processing
1001  */
1002 static int
1003 inject_message (void *cls,
1004                 const struct GNUNET_MessageHeader *message)
1005 {
1006   uint16_t msize = ntohs (message->size);
1007   const struct GNUNET_STATISTICS_SetMessage *sm;
1008
1009   sm = (const struct GNUNET_STATISTICS_SetMessage *) message;
1010   if ( (sizeof (struct GNUNET_STATISTICS_SetMessage) > msize) ||
1011        (GNUNET_OK !=
1012         check_set (NULL,
1013                    sm)) )
1014   {
1015     GNUNET_break (0);
1016     return GNUNET_SYSERR;
1017   }
1018   handle_set (NULL,
1019               sm);
1020   return GNUNET_OK;
1021 }
1022
1023
1024 /**
1025  * Load persistent values from disk.  Disk format is exactly the same
1026  * format that we also use for setting the values over the network.
1027  */
1028 static void
1029 load ()
1030 {
1031   char *fn;
1032   struct GNUNET_BIO_ReadHandle *rh;
1033   uint64_t fsize;
1034   char *buf;
1035   struct GNUNET_MessageStreamTokenizer *mst;
1036
1037   if (GNUNET_OK !=
1038       GNUNET_CONFIGURATION_get_value_filename (cfg,
1039                                                "STATISTICS",
1040                                                "DATABASE",
1041                                                &fn))
1042   {
1043     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
1044                                "STATISTICS",
1045                                "DATABASE");
1046     return;
1047   }
1048   if ( (GNUNET_OK !=
1049         GNUNET_DISK_file_size (fn,
1050                                &fsize,
1051                                GNUNET_NO,
1052                                GNUNET_YES)) ||
1053        (0 == fsize) )
1054   {
1055     GNUNET_free (fn);
1056     return;
1057   }
1058   buf = GNUNET_malloc (fsize);
1059   rh = GNUNET_BIO_read_open (fn);
1060   if (! rh)
1061   {
1062     GNUNET_free (buf);
1063     GNUNET_free (fn);
1064     return;
1065   }
1066   if (GNUNET_OK !=
1067       GNUNET_BIO_read (rh,
1068                        fn,
1069                        buf,
1070                        fsize))
1071   {
1072     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
1073                               "read",
1074                               fn);
1075     GNUNET_break (GNUNET_OK ==
1076                   GNUNET_BIO_read_close (rh,
1077                                          NULL));
1078     GNUNET_free (buf);
1079     GNUNET_free (fn);
1080     return;
1081   }
1082   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1083               _("Loading %llu bytes of statistics from `%s'\n"),
1084               (unsigned long long) fsize,
1085               fn);
1086   mst = GNUNET_MST_create (&inject_message,
1087                            NULL);
1088   GNUNET_break (GNUNET_OK ==
1089                 GNUNET_MST_from_buffer (mst,
1090                                         buf,
1091                                         (size_t) fsize,
1092                                         GNUNET_YES,
1093                                         GNUNET_NO));
1094   GNUNET_MST_destroy (mst);
1095   GNUNET_free (buf);
1096   GNUNET_break (GNUNET_OK ==
1097                 GNUNET_BIO_read_close (rh,
1098                                        NULL));
1099   GNUNET_free (fn);
1100 }
1101
1102
1103 /**
1104  * Process statistics requests.
1105  *
1106  * @param cls closure
1107  * @param c configuration to use
1108  * @param service the initialized service
1109  */
1110 static void
1111 run (void *cls,
1112      const struct GNUNET_CONFIGURATION_Handle *c,
1113      struct GNUNET_SERVICE_Handle *service)
1114 {
1115   cfg = c;
1116   nc = GNUNET_notification_context_create (16);
1117   load ();
1118   GNUNET_SCHEDULER_add_shutdown (&shutdown_task,
1119                                  NULL);
1120 }
1121
1122
1123 /**
1124  * Define "main" method using service macro.
1125  */
1126 GNUNET_SERVICE_MAIN
1127 ("statistics",
1128  GNUNET_SERVICE_OPTION_SOFT_SHUTDOWN,
1129  &run,
1130  &client_connect_cb,
1131  &client_disconnect_cb,
1132  NULL,
1133  GNUNET_MQ_hd_var_size (set,
1134                         GNUNET_MESSAGE_TYPE_STATISTICS_SET,
1135                         struct GNUNET_STATISTICS_SetMessage,
1136                         NULL),
1137  GNUNET_MQ_hd_var_size (get,
1138                         GNUNET_MESSAGE_TYPE_STATISTICS_GET,
1139                         struct GNUNET_MessageHeader,
1140                         NULL),
1141  GNUNET_MQ_hd_var_size (watch,
1142                         GNUNET_MESSAGE_TYPE_STATISTICS_WATCH,
1143                         struct GNUNET_MessageHeader,
1144                         NULL),
1145  GNUNET_MQ_hd_fixed_size (disconnect,
1146                           GNUNET_MESSAGE_TYPE_STATISTICS_DISCONNECT,
1147                           struct GNUNET_MessageHeader,
1148                           NULL),
1149  GNUNET_MQ_handler_end ());
1150
1151
1152 #if defined(LINUX) && defined(__GLIBC__)
1153 #include <malloc.h>
1154
1155 /**
1156  * MINIMIZE heap size (way below 128k) since this process doesn't need much.
1157  */
1158 void __attribute__ ((constructor))
1159 GNUNET_STATISTICS_memory_init ()
1160 {
1161   mallopt (M_TRIM_THRESHOLD, 4 * 1024);
1162   mallopt (M_TOP_PAD, 1 * 1024);
1163   malloc_trim (0);
1164 }
1165 #endif
1166
1167
1168 /* end of gnunet-service-statistics.c */