reduce loop counters to more practical levels
[oweals/gnunet.git] / src / datacache / datacache.c
1 /*
2      This file is part of GNUnet
3      Copyright (C) 2004, 2005, 2006, 2007, 2009, 2010, 2015 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  * @file datacache/datacache.c
22  * @brief datacache API implementation
23  * @author Christian Grothoff
24  */
25 #include "platform.h"
26 #include "gnunet_util_lib.h"
27 #include "gnunet_datacache_lib.h"
28 #include "gnunet_statistics_service.h"
29 #include "gnunet_datacache_plugin.h"
30
31
32 #define LOG(kind,...) GNUNET_log_from (kind, "datacache", __VA_ARGS__)
33
34 #define LOG_STRERROR_FILE(kind,op,fn) GNUNET_log_from_strerror_file (kind, "datacache", op, fn)
35
36 /**
37  * Internal state of the datacache library.
38  */
39 struct GNUNET_DATACACHE_Handle
40 {
41
42   /**
43    * Bloomfilter to quickly tell if we don't have the content.
44    */
45   struct GNUNET_CONTAINER_BloomFilter *filter;
46
47   /**
48    * Our configuration.
49    */
50   const struct GNUNET_CONFIGURATION_Handle *cfg;
51
52   /**
53    * Opaque handle for the statistics service.
54    */
55   struct GNUNET_STATISTICS_Handle *stats;
56
57   /**
58    * Configuration section to use.
59    */
60   char *section;
61
62   /**
63    * API of the transport as returned by the plugin's
64    * initialization function.
65    */
66   struct GNUNET_DATACACHE_PluginFunctions *api;
67
68   /**
69    * Short name for the plugin (i.e. "sqlite").
70    */
71   char *short_name;
72
73   /**
74    * Name of the library (i.e. "gnunet_plugin_datacache_sqlite").
75    */
76   char *lib_name;
77
78   /**
79    * Name for the bloom filter file.
80    */
81   char *bloom_name;
82
83   /**
84    * Environment provided to our plugin.
85    */
86   struct GNUNET_DATACACHE_PluginEnvironment env;
87
88   /**
89    * How much space is in use right now?
90    */
91   unsigned long long utilization;
92
93 };
94
95
96 /**
97  * Function called by plugins to notify the datacache
98  * about content deletions.
99  *
100  * @param cls closure
101  * @param key key of the content that was deleted
102  * @param size number of bytes that were made available
103  */
104 static void
105 env_delete_notify (void *cls,
106                    const struct GNUNET_HashCode *key,
107                    size_t size)
108 {
109   struct GNUNET_DATACACHE_Handle *h = cls;
110
111   LOG (GNUNET_ERROR_TYPE_DEBUG,
112        "Content under key `%s' discarded\n",
113        GNUNET_h2s (key));
114   GNUNET_assert (h->utilization >= size);
115   h->utilization -= size;
116   GNUNET_CONTAINER_bloomfilter_remove (h->filter,
117                                        key);
118   GNUNET_STATISTICS_update (h->stats,
119                             gettext_noop ("# bytes stored"),
120                             - (long long) size,
121                             GNUNET_NO);
122   GNUNET_STATISTICS_update (h->stats,
123                             gettext_noop ("# items stored"),
124                             -1,
125                             GNUNET_NO);
126 }
127
128
129 /**
130  * Create a data cache.
131  *
132  * @param cfg configuration to use
133  * @param section section in the configuration that contains our options
134  * @return handle to use to access the service
135  */
136 struct GNUNET_DATACACHE_Handle *
137 GNUNET_DATACACHE_create (const struct GNUNET_CONFIGURATION_Handle *cfg,
138                          const char *section)
139 {
140   unsigned int bf_size;
141   unsigned long long quota;
142   struct GNUNET_DATACACHE_Handle *ret;
143   char *libname;
144   char *name;
145
146   if (GNUNET_OK !=
147       GNUNET_CONFIGURATION_get_value_size (cfg,
148                                            section,
149                                            "QUOTA",
150                                            &quota))
151   {
152     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
153                                section,
154                                "QUOTA");
155     return NULL;
156   }
157   if (GNUNET_OK !=
158       GNUNET_CONFIGURATION_get_value_string (cfg,
159                                              section,
160                                              "DATABASE",
161                                              &name))
162   {
163     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
164                                section,
165                                "DATABASE");
166     return NULL;
167   }
168   bf_size = quota / 32;         /* 8 bit per entry, 1 bit per 32 kb in DB */
169
170   ret = GNUNET_new (struct GNUNET_DATACACHE_Handle);
171
172   if (GNUNET_YES !=
173       GNUNET_CONFIGURATION_get_value_yesno (cfg,
174                                             section,
175                                             "DISABLE_BF"))
176   {
177     if (GNUNET_YES !=
178         GNUNET_CONFIGURATION_get_value_yesno (cfg,
179                                               section,
180                                               "DISABLE_BF_RC"))
181     {
182       ret->bloom_name = GNUNET_DISK_mktemp ("gnunet-datacachebloom");
183     }
184     if (NULL != ret->bloom_name)
185     {
186       ret->filter = GNUNET_CONTAINER_bloomfilter_load (ret->bloom_name,
187                                                        quota / 1024,     /* 8 bit per entry in DB, expect 1k entries */
188                                                        5);
189     }
190     if (NULL == ret->filter)
191     {
192       ret->filter = GNUNET_CONTAINER_bloomfilter_init (NULL,
193                                                        bf_size,
194                                                        5); /* approx. 3% false positives at max use */
195     }
196   }
197   ret->stats = GNUNET_STATISTICS_create ("datacache", cfg);
198   ret->section = GNUNET_strdup (section);
199   ret->env.cfg = cfg;
200   ret->env.delete_notify = &env_delete_notify;
201   ret->env.section = ret->section;
202   ret->env.cls = ret;
203   ret->env.delete_notify = &env_delete_notify;
204   ret->env.quota = quota;
205   LOG (GNUNET_ERROR_TYPE_INFO,
206        _("Loading `%s' datacache plugin\n"),
207        name);
208   GNUNET_asprintf (&libname,
209                    "libgnunet_plugin_datacache_%s",
210                    name);
211   ret->short_name = name;
212   ret->lib_name = libname;
213   ret->api = GNUNET_PLUGIN_load (libname, &ret->env);
214   if (ret->api == NULL)
215   {
216     LOG (GNUNET_ERROR_TYPE_ERROR,
217          _("Failed to load datacache plugin for `%s'\n"),
218          name);
219     GNUNET_DATACACHE_destroy (ret);
220     return NULL;
221   }
222   return ret;
223 }
224
225
226 /**
227  * Destroy a data cache (and free associated resources).
228  *
229  * @param h handle to the datastore
230  */
231 void
232 GNUNET_DATACACHE_destroy (struct GNUNET_DATACACHE_Handle *h)
233 {
234   if (NULL != h->filter)
235     GNUNET_CONTAINER_bloomfilter_free (h->filter);
236   if (NULL != h->api)
237     GNUNET_break (NULL ==
238                   GNUNET_PLUGIN_unload (h->lib_name,
239                                         h->api));
240   GNUNET_free (h->lib_name);
241   GNUNET_free (h->short_name);
242   GNUNET_free (h->section);
243   if (NULL != h->bloom_name)
244   {
245     if (0 != UNLINK (h->bloom_name))
246       GNUNET_log_from_strerror_file (GNUNET_ERROR_TYPE_WARNING,
247                                      "datacache",
248                                      "unlink",
249                                      h->bloom_name);
250     GNUNET_free (h->bloom_name);
251   }
252   GNUNET_STATISTICS_destroy (h->stats,
253                              GNUNET_NO);
254   GNUNET_free (h);
255 }
256
257
258 /**
259  * Store an item in the datastore.
260  *
261  * @param h handle to the datacache
262  * @param key key to store data under
263  * @param data_size number of bytes in @a data
264  * @param data data to store
265  * @param type type of the value
266  * @param discard_time when to discard the value in any case
267  * @param path_info_len number of entries in @a path_info
268  * @param path_info a path through the network
269  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error, #GNUNET_NO if duplicate
270  */
271 int
272 GNUNET_DATACACHE_put (struct GNUNET_DATACACHE_Handle *h,
273                       const struct GNUNET_HashCode *key,
274                       size_t data_size,
275                       const char *data,
276                       enum GNUNET_BLOCK_Type type,
277                       struct GNUNET_TIME_Absolute discard_time,
278                       unsigned int path_info_len,
279                       const struct GNUNET_PeerIdentity *path_info)
280 {
281   ssize_t used;
282
283   used = h->api->put (h->api->cls,
284                       key,
285                       data_size,
286                       data,
287                       type,
288                       discard_time,
289                       path_info_len,
290                       path_info);
291   if (-1 == used)
292   {
293     GNUNET_break (0);
294     return GNUNET_SYSERR;
295   }
296   if (0 == used)
297   {
298     /* duplicate */
299     return GNUNET_NO;
300   }
301   LOG (GNUNET_ERROR_TYPE_DEBUG,
302        "Stored data under key `%s' in cache\n",
303        GNUNET_h2s (key));
304   if (NULL != h->filter)
305     GNUNET_CONTAINER_bloomfilter_add (h->filter,
306                                       key);
307   GNUNET_STATISTICS_update (h->stats,
308                             gettext_noop ("# bytes stored"),
309                             used,
310                             GNUNET_NO);
311   GNUNET_STATISTICS_update (h->stats,
312                             gettext_noop ("# items stored"),
313                             1,
314                             GNUNET_NO);
315   while (h->utilization + used > h->env.quota)
316     GNUNET_assert (GNUNET_OK == h->api->del (h->api->cls));
317   h->utilization += used;
318   return GNUNET_OK;
319 }
320
321
322 /**
323  * Iterate over the results for a particular key
324  * in the datacache.
325  *
326  * @param h handle to the datacache
327  * @param key what to look up
328  * @param type entries of which type are relevant?
329  * @param iter maybe NULL (to just count)
330  * @param iter_cls closure for @a iter
331  * @return the number of results found
332  */
333 unsigned int
334 GNUNET_DATACACHE_get (struct GNUNET_DATACACHE_Handle *h,
335                       const struct GNUNET_HashCode *key,
336                       enum GNUNET_BLOCK_Type type,
337                       GNUNET_DATACACHE_Iterator iter,
338                       void *iter_cls)
339 {
340   GNUNET_STATISTICS_update (h->stats,
341                             gettext_noop ("# requests received"),
342                             1,
343                             GNUNET_NO);
344   LOG (GNUNET_ERROR_TYPE_DEBUG,
345        "Processing request for key `%s'\n",
346        GNUNET_h2s (key));
347   if ( (NULL != h->filter) &&
348        (GNUNET_OK != GNUNET_CONTAINER_bloomfilter_test (h->filter, key)) )
349   {
350     GNUNET_STATISTICS_update (h->stats,
351                               gettext_noop ("# requests filtered by bloom filter"),
352                               1,
353                               GNUNET_NO);
354     LOG (GNUNET_ERROR_TYPE_DEBUG,
355          "Bloomfilter filters request for key `%s'\n",
356          GNUNET_h2s (key));
357     return 0;                   /* can not be present */
358   }
359   return h->api->get (h->api->cls,
360                       key,
361                       type,
362                       iter,
363                       iter_cls);
364 }
365
366
367 /**
368  * Obtain a random element from the datacache.
369  *
370  * @param h handle to the datacache
371  * @param iter maybe NULL (to just count)
372  * @param iter_cls closure for @a iter
373  * @return the number of results found (zero or 1)
374  */
375 unsigned int
376 GNUNET_DATACACHE_get_random (struct GNUNET_DATACACHE_Handle *h,
377                              GNUNET_DATACACHE_Iterator iter,
378                              void *iter_cls)
379 {
380   GNUNET_STATISTICS_update (h->stats,
381                             gettext_noop ("# requests for random value received"),
382                             1,
383                             GNUNET_NO);
384   LOG (GNUNET_ERROR_TYPE_DEBUG,
385        "Processing request for random value\n");
386   return h->api->get_random (h->api->cls,
387                              iter,
388                              iter_cls);
389 }
390
391
392 /**
393  * Iterate over the results that are "close" to a particular key in
394  * the datacache.  "close" is defined as numerically larger than @a
395  * key (when interpreted as a circular address space), with small
396  * distance.
397  *
398  * @param h handle to the datacache
399  * @param key area of the keyspace to look into
400  * @param num_results number of results that should be returned to @a iter
401  * @param iter maybe NULL (to just count)
402  * @param iter_cls closure for @a iter
403  * @return the number of results found
404  */
405 unsigned int
406 GNUNET_DATACACHE_get_closest (struct GNUNET_DATACACHE_Handle *h,
407                               const struct GNUNET_HashCode *key,
408                               unsigned int num_results,
409                               GNUNET_DATACACHE_Iterator iter,
410                               void *iter_cls)
411 {
412   GNUNET_STATISTICS_update (h->stats,
413                             gettext_noop ("# proximity search requests received"),
414                             1,
415                             GNUNET_NO);
416   LOG (GNUNET_ERROR_TYPE_DEBUG,
417        "Processing proximity search at `%s'\n",
418        GNUNET_h2s (key));
419   return h->api->get_closest (h->api->cls,
420                               key,
421                               num_results,
422                               iter,
423                               iter_cls);
424 }
425
426
427 /* end of datacache.c */