3d67ffc22b2a420d795eb3239e95cbbffd3569bf
[oweals/gnunet.git] / src / datacache / plugin_datacache_sqlite.c
1 /*
2      This file is part of GNUnet
3      (C) 2006, 2009 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 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., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file datacache/plugin_datacache_sqlite.c
23  * @brief sqlite for an implementation of a database backend for the datacache
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet_util_lib.h"
28 #include "gnunet_datacache_plugin.h"
29 #include <sqlite3.h>
30
31 #define DEBUG_DATACACHE_SQLITE GNUNET_NO
32
33 /**
34  * How much overhead do we assume per entry in the
35  * datacache?
36  */
37 #define OVERHEAD (sizeof(GNUNET_HashCode) + 32)
38
39 /**
40  * Context for all functions in this plugin.
41  */
42 struct Plugin
43 {
44   /**
45    * Our execution environment.
46    */
47   struct GNUNET_DATACACHE_PluginEnvironment *env;
48
49   /**
50    * Handle to the sqlite database.
51    */
52   sqlite3 *dbh;
53
54   /**
55    * Filename used for the DB.
56    */
57   char *fn;
58 };
59
60
61 /**
62  * Log an error message at log-level 'level' that indicates
63  * a failure of the command 'cmd' on file 'filename'
64  * with the message given by strerror(errno).
65  */
66 #define LOG_SQLITE(db, level, cmd) do { GNUNET_log(level, _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, sqlite3_errmsg(db)); } while(0)
67
68
69 #define SQLITE3_EXEC(db, cmd) do { emsg = NULL; if (SQLITE_OK != sqlite3_exec(db, cmd, NULL, NULL, &emsg)) { GNUNET_log(GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, _("`%s' failed at %s:%d with error: %s\n"), "sqlite3_exec", __FILE__, __LINE__, emsg); sqlite3_free(emsg); } } while(0)
70
71
72 /**
73  * @brief Prepare a SQL statement
74  */
75 static int
76 sq_prepare (sqlite3 * dbh, const char *zSql,    /* SQL statement, UTF-8 encoded */
77             sqlite3_stmt ** ppStmt)
78 {                               /* OUT: Statement handle */
79   char *dummy;
80
81   return sqlite3_prepare (dbh, zSql, strlen (zSql), ppStmt,
82                           (const char **) &dummy);
83 }
84
85
86 /**
87  * Store an item in the datastore.
88  *
89  * @param cls closure (our "struct Plugin")
90  * @param key key to store data under
91  * @param size number of bytes in data
92  * @param data data to store
93  * @param type type of the value
94  * @param discard_time when to discard the value in any case
95  * @return 0 on error, number of bytes used otherwise
96  */
97 static size_t
98 sqlite_plugin_put (void *cls, const GNUNET_HashCode * key, size_t size,
99                    const char *data, enum GNUNET_BLOCK_Type type,
100                    struct GNUNET_TIME_Absolute discard_time)
101 {
102   struct Plugin *plugin = cls;
103   sqlite3_stmt *stmt;
104   int64_t dval;
105
106 #if DEBUG_DATACACHE_SQLITE
107   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
108               "Processing `%s' of %u bytes with key `%4s' and expiration %llums\n",
109               "PUT", (unsigned int) size, GNUNET_h2s (key),
110               (unsigned long long)
111               GNUNET_TIME_absolute_get_remaining (discard_time).rel_value);
112 #endif
113   dval = (int64_t) discard_time.abs_value;
114   if (dval < 0)
115     dval = INT64_MAX;
116   if (sq_prepare
117       (plugin->dbh,
118        "INSERT INTO ds090 " "(type, expire, key, value) " "VALUES (?, ?, ?, ?)",
119        &stmt) != SQLITE_OK)
120   {
121     GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
122                 _("`%s' failed at %s:%d with error: %s\n"), "sq_prepare",
123                 __FILE__, __LINE__, sqlite3_errmsg (plugin->dbh));
124     return 0;
125   }
126   if ((SQLITE_OK != sqlite3_bind_int (stmt, 1, type)) ||
127       (SQLITE_OK != sqlite3_bind_int64 (stmt, 2, dval)) ||
128       (SQLITE_OK !=
129        sqlite3_bind_blob (stmt, 3, key, sizeof (GNUNET_HashCode),
130                           SQLITE_TRANSIENT)) ||
131       (SQLITE_OK != sqlite3_bind_blob (stmt, 4, data, size, SQLITE_TRANSIENT)))
132   {
133     LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
134                 "sqlite3_bind_xxx");
135     sqlite3_finalize (stmt);
136     return 0;
137   }
138   if (SQLITE_DONE != sqlite3_step (stmt))
139   {
140     LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
141                 "sqlite3_step");
142     sqlite3_finalize (stmt);
143     return 0;
144   }
145   if (SQLITE_OK != sqlite3_finalize (stmt))
146     LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
147                 "sqlite3_finalize");
148   return size + OVERHEAD;
149 }
150
151
152 /**
153  * Iterate over the results for a particular key
154  * in the datastore.
155  *
156  * @param cls closure (our "struct Plugin")
157  * @param key
158  * @param type entries of which type are relevant?
159  * @param iter maybe NULL (to just count)
160  * @param iter_cls closure for iter
161  * @return the number of results found
162  */
163 static unsigned int
164 sqlite_plugin_get (void *cls, const GNUNET_HashCode * key,
165                    enum GNUNET_BLOCK_Type type, GNUNET_DATACACHE_Iterator iter,
166                    void *iter_cls)
167 {
168   struct Plugin *plugin = cls;
169   sqlite3_stmt *stmt;
170   struct GNUNET_TIME_Absolute now;
171   struct GNUNET_TIME_Absolute exp;
172   unsigned int size;
173   const char *dat;
174   unsigned int cnt;
175   unsigned int off;
176   unsigned int total;
177   char scratch[256];
178   int64_t ntime;
179
180   now = GNUNET_TIME_absolute_get ();
181 #if DEBUG_DATACACHE_SQLITE
182   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Processing `%s' for key `%4s'\n", "GET",
183               GNUNET_h2s (key));
184 #endif
185   if (sq_prepare
186       (plugin->dbh,
187        "SELECT count(*) FROM ds090 WHERE key=? AND type=? AND expire >= ?",
188        &stmt) != SQLITE_OK)
189   {
190     GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
191                 _("`%s' failed at %s:%d with error: %s\n"), "sq_prepare",
192                 __FILE__, __LINE__, sqlite3_errmsg (plugin->dbh));
193     return 0;
194   }
195   ntime = (int64_t) now.abs_value;
196   GNUNET_assert (ntime >= 0);
197   if ((SQLITE_OK !=
198        sqlite3_bind_blob (stmt, 1, key, sizeof (GNUNET_HashCode),
199                           SQLITE_TRANSIENT)) ||
200       (SQLITE_OK != sqlite3_bind_int (stmt, 2, type)) ||
201       (SQLITE_OK != sqlite3_bind_int64 (stmt, 3, now.abs_value)))
202   {
203     LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
204                 "sqlite3_bind_xxx");
205     sqlite3_finalize (stmt);
206     return 0;
207   }
208
209   if (SQLITE_ROW != sqlite3_step (stmt))
210   {
211     LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
212                 "sqlite_step");
213     sqlite3_finalize (stmt);
214     return 0;
215   }
216   total = sqlite3_column_int (stmt, 0);
217   sqlite3_finalize (stmt);
218   if ((total == 0) || (iter == NULL))
219     return total;
220
221   cnt = 0;
222   off = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, total);
223   while (cnt < total)
224   {
225     off = (off + 1) % total;
226     GNUNET_snprintf (scratch, sizeof (scratch),
227                      "SELECT value,expire FROM ds090 WHERE key=? AND type=? AND expire >= ? LIMIT 1 OFFSET %u",
228                      off);
229     if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
230     {
231       GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
232                   _("`%s' failed at %s:%d with error: %s\n"), "sq_prepare",
233                   __FILE__, __LINE__, sqlite3_errmsg (plugin->dbh));
234       return cnt;
235     }
236     if ((SQLITE_OK !=
237          sqlite3_bind_blob (stmt, 1, key, sizeof (GNUNET_HashCode),
238                             SQLITE_TRANSIENT)) ||
239         (SQLITE_OK != sqlite3_bind_int (stmt, 2, type)) ||
240         (SQLITE_OK != sqlite3_bind_int64 (stmt, 3, now.abs_value)))
241     {
242       LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
243                   "sqlite3_bind_xxx");
244       sqlite3_finalize (stmt);
245       return cnt;
246     }
247     if (sqlite3_step (stmt) != SQLITE_ROW)
248       break;
249     size = sqlite3_column_bytes (stmt, 0);
250     dat = sqlite3_column_blob (stmt, 0);
251     exp.abs_value = sqlite3_column_int64 (stmt, 1);
252     ntime = (int64_t) exp.abs_value;
253     if (ntime == INT64_MAX)
254       exp = GNUNET_TIME_UNIT_FOREVER_ABS;
255     cnt++;
256     if (GNUNET_OK != iter (iter_cls, exp, key, size, dat, type))
257     {
258       sqlite3_finalize (stmt);
259       break;
260     }
261     sqlite3_finalize (stmt);
262   }
263   return cnt;
264 }
265
266
267 /**
268  * Delete the entry with the lowest expiration value
269  * from the datacache right now.
270  * 
271  * @param cls closure (our "struct Plugin")
272  * @return GNUNET_OK on success, GNUNET_SYSERR on error
273  */
274 static int
275 sqlite_plugin_del (void *cls)
276 {
277   struct Plugin *plugin = cls;
278   unsigned int dsize;
279   unsigned int dtype;
280   sqlite3_stmt *stmt;
281   sqlite3_stmt *dstmt;
282   char blob[65536];
283   GNUNET_HashCode hc;
284
285 #if DEBUG_DATACACHE_SQLITE
286   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Processing `%s'\n", "DEL");
287 #endif
288   stmt = NULL;
289   dstmt = NULL;
290   if (sq_prepare
291       (plugin->dbh,
292        "SELECT type, key, value FROM ds090 ORDER BY expire ASC LIMIT 1",
293        &stmt) != SQLITE_OK)
294   {
295     GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
296                 _("`%s' failed at %s:%d with error: %s\n"), "sq_prepare",
297                 __FILE__, __LINE__, sqlite3_errmsg (plugin->dbh));
298     if (stmt != NULL)
299       (void) sqlite3_finalize (stmt);
300     return GNUNET_SYSERR;
301   }
302   if (SQLITE_ROW != sqlite3_step (stmt))
303   {
304     GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
305                 _("`%s' failed at %s:%d with error: %s\n"), "sqlite3_step",
306                 __FILE__, __LINE__, sqlite3_errmsg (plugin->dbh));
307     (void) sqlite3_finalize (stmt);
308     return GNUNET_SYSERR;
309   }
310   dtype = sqlite3_column_int (stmt, 0);
311   GNUNET_break (sqlite3_column_bytes (stmt, 1) == sizeof (GNUNET_HashCode));
312   dsize = sqlite3_column_bytes (stmt, 2);
313   GNUNET_assert (dsize <= sizeof (blob));
314   memcpy (blob, sqlite3_column_blob (stmt, 2), dsize);
315   memcpy (&hc, sqlite3_column_blob (stmt, 1), sizeof (GNUNET_HashCode));
316   if (SQLITE_OK != sqlite3_finalize (stmt))
317     GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
318                 _("`%s' failed at %s:%d with error: %s\n"), "sqlite3_step",
319                 __FILE__, __LINE__, sqlite3_errmsg (plugin->dbh));
320   if (sq_prepare
321       (plugin->dbh, "DELETE FROM ds090 " "WHERE key=? AND value=? AND type=?",
322        &dstmt) != SQLITE_OK)
323   {
324     GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
325                 _("`%s' failed at %s:%d with error: %s\n"), "sq_prepare",
326                 __FILE__, __LINE__, sqlite3_errmsg (plugin->dbh));
327     if (stmt != NULL)
328       (void) sqlite3_finalize (stmt);
329     return GNUNET_SYSERR;
330   }
331   if ((SQLITE_OK !=
332        sqlite3_bind_blob (dstmt, 1, &hc, sizeof (GNUNET_HashCode),
333                           SQLITE_TRANSIENT)) ||
334       (SQLITE_OK != sqlite3_bind_blob (dstmt, 2, blob, dsize, SQLITE_TRANSIENT))
335       || (SQLITE_OK != sqlite3_bind_int (dstmt, 3, dtype)))
336   {
337     GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
338                 _("`%s' failed at %s:%d with error: %s\n"), "sqlite3_bind",
339                 __FILE__, __LINE__, sqlite3_errmsg (plugin->dbh));
340     (void) sqlite3_finalize (dstmt);
341     return GNUNET_SYSERR;
342   }
343   if (sqlite3_step (dstmt) != SQLITE_DONE)
344   {
345     GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
346                 _("`%s' failed at %s:%d with error: %s\n"), "sqlite3_step",
347                 __FILE__, __LINE__, sqlite3_errmsg (plugin->dbh));
348     (void) sqlite3_finalize (dstmt);
349     return GNUNET_SYSERR;
350   }
351   plugin->env->delete_notify (plugin->env->cls, &hc, dsize + OVERHEAD);
352   if (SQLITE_OK != sqlite3_finalize (dstmt))
353     GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
354                 _("`%s' failed at %s:%d with error: %s\n"), "sqlite3_finalize",
355                 __FILE__, __LINE__, sqlite3_errmsg (plugin->dbh));
356   return GNUNET_OK;
357 }
358
359
360 /**
361  * Entry point for the plugin.
362  *
363  * @param cls closure (the "struct GNUNET_DATACACHE_PluginEnvironmnet")
364  * @return the plugin's closure (our "struct Plugin")
365  */
366 void *
367 libgnunet_plugin_datacache_sqlite_init (void *cls)
368 {
369   struct GNUNET_DATACACHE_PluginEnvironment *env = cls;
370   struct GNUNET_DATACACHE_PluginFunctions *api;
371   struct Plugin *plugin;
372   char *fn;
373   char *fn_utf8;
374   sqlite3 *dbh;
375   char *emsg;
376
377   fn = GNUNET_DISK_mktemp ("gnunet-datacache");
378   if (fn == NULL)
379   {
380     GNUNET_break (0);
381     return NULL;
382   }
383 #ifdef ENABLE_NLS
384   fn_utf8 = GNUNET_STRINGS_to_utf8 (fn, strlen (fn), nl_langinfo (CODESET));
385 #else
386   /* good luck */
387   fn_utf8 = GNUNET_STRINGS_to_utf8 (fn, strlen (fn), "UTF-8");
388 #endif
389   if (SQLITE_OK != sqlite3_open (fn_utf8, &dbh))
390   {
391     GNUNET_free (fn);
392     GNUNET_free (fn_utf8);
393     return NULL;
394   }
395   GNUNET_free (fn);
396
397   SQLITE3_EXEC (dbh, "PRAGMA temp_store=MEMORY");
398   SQLITE3_EXEC (dbh, "PRAGMA locking_mode=EXCLUSIVE");
399   SQLITE3_EXEC (dbh, "PRAGMA journal_mode=OFF");
400   SQLITE3_EXEC (dbh, "PRAGMA synchronous=OFF");
401   SQLITE3_EXEC (dbh, "PRAGMA count_changes=OFF");
402   SQLITE3_EXEC (dbh, "PRAGMA page_size=4092");
403   SQLITE3_EXEC (dbh,
404                 "CREATE TABLE ds090 (" "  type INTEGER NOT NULL DEFAULT 0,"
405                 "  expire INTEGER NOT NULL DEFAULT 0,"
406                 "  key BLOB NOT NULL DEFAULT '',"
407                 "  value BLOB NOT NULL DEFAULT '')");
408   SQLITE3_EXEC (dbh, "CREATE INDEX idx_hashidx ON ds090 (key,type,expire)");
409   plugin = GNUNET_malloc (sizeof (struct Plugin));
410   plugin->env = env;
411   plugin->dbh = dbh;
412   plugin->fn = fn_utf8;
413   api = GNUNET_malloc (sizeof (struct GNUNET_DATACACHE_PluginFunctions));
414   api->cls = plugin;
415   api->get = &sqlite_plugin_get;
416   api->put = &sqlite_plugin_put;
417   api->del = &sqlite_plugin_del;
418   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, "sqlite",
419                    _("Sqlite datacache running\n"));
420   return api;
421 }
422
423 // explain SELECT type FROM gn090 WHERE NOT EXISTS (SELECT 1 from gn090 WHERE expire < 42 LIMIT 1) OR expire < 42 ORDER BY repl DESC, Random() LIMIT 1;
424
425
426 /**
427  * Exit point from the plugin.
428  *
429  * @param cls closure (our "struct Plugin")
430  * @return NULL
431  */
432 void *
433 libgnunet_plugin_datacache_sqlite_done (void *cls)
434 {
435   struct GNUNET_DATACACHE_PluginFunctions *api = cls;
436   struct Plugin *plugin = api->cls;
437   int result;
438
439 #if SQLITE_VERSION_NUMBER >= 3007000
440   sqlite3_stmt *stmt;
441 #endif
442
443 #if !WINDOWS || defined(__CYGWIN__)
444   if (0 != UNLINK (plugin->fn))
445     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", plugin->fn);
446   GNUNET_free (plugin->fn);
447 #endif
448   result = sqlite3_close (plugin->dbh);
449 #if SQLITE_VERSION_NUMBER >= 3007000
450   if (result == SQLITE_BUSY)
451   {
452     GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, "sqlite",
453                      _
454                      ("Tried to close sqlite without finalizing all prepared statements.\n"));
455     stmt = sqlite3_next_stmt (plugin->dbh, NULL);
456     while (stmt != NULL)
457     {
458 #if DEBUG_SQLITE
459       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
460                        "Closing statement %p\n", stmt);
461 #endif
462       result = sqlite3_finalize (stmt);
463 #if DEBUG_SQLITE
464       if (result != SQLITE_OK)
465         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "sqlite",
466                          "Failed to close statement %p: %d\n", stmt, result);
467 #endif
468       stmt = sqlite3_next_stmt (plugin->dbh, NULL);
469     }
470     result = sqlite3_close (plugin->dbh);
471   }
472 #endif
473   if (SQLITE_OK != result)
474     LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close");
475
476 #if WINDOWS && !defined(__CYGWIN__)
477   if (0 != UNLINK (plugin->fn))
478     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", plugin->fn);
479   GNUNET_free (plugin->fn);
480 #endif
481   GNUNET_free (plugin);
482   GNUNET_free (api);
483   return NULL;
484 }
485
486
487
488 /* end of plugin_datacache_sqlite.c */