rounding
[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 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 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 "plugin_datacache.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   return sqlite3_prepare (dbh,
81                           zSql,
82                           strlen (zSql), ppStmt, (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 uint32_t 
98 sqlite_plugin_put (void *cls,
99                    const GNUNET_HashCode * key,
100                    uint32_t size,
101                    const char *data,
102                    uint32_t type,
103                    struct GNUNET_TIME_Absolute discard_time)
104 {
105   struct Plugin *plugin = cls;
106   sqlite3_stmt *stmt;
107
108 #if DEBUG_DATACACHE_SQLITE
109   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
110               "Processing `%s' of %u bytes with key `%4s' and expiration %llums\n",
111               "PUT",
112               (unsigned int) size,
113               GNUNET_h2s (key),
114               (unsigned long long) GNUNET_TIME_absolute_get_remaining (discard_time).value);
115 #endif
116   if (sq_prepare (plugin->dbh,
117                   "INSERT INTO ds090 "
118                   "(type, expire, key, value) "
119                   "VALUES (?, ?, ?, ?)", &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"),
123                   "sq_prepare", __FILE__, __LINE__, 
124                   sqlite3_errmsg (plugin->dbh));
125       return 0;
126     }
127   if ( (SQLITE_OK != sqlite3_bind_int (stmt, 1, type)) ||
128        (SQLITE_OK != sqlite3_bind_int64 (stmt, 2, discard_time.value)) ||
129        (SQLITE_OK != 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,
134                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, 
135                   "sqlite3_bind_xxx");
136       sqlite3_finalize (stmt);
137       return 0;
138     }
139   if (SQLITE_DONE != sqlite3_step (stmt))
140     {
141       LOG_SQLITE (plugin->dbh,
142                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, 
143                   "sqlite3_step");
144       sqlite3_finalize (stmt);
145       return 0;
146     }
147   if (SQLITE_OK != sqlite3_finalize (stmt))
148     LOG_SQLITE (plugin->dbh,
149                 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, 
150                 "sqlite3_finalize");
151   return size + OVERHEAD;
152 }
153
154
155 /**
156  * Iterate over the results for a particular key
157  * in the datastore.
158  *
159  * @param cls closure (our "struct Plugin")
160  * @param key
161  * @param type entries of which type are relevant?
162  * @param iter maybe NULL (to just count)
163  * @param iter_cls closure for iter
164  * @return the number of results found
165  */
166 static unsigned int 
167 sqlite_plugin_get (void *cls,
168                    const GNUNET_HashCode * key,
169                    uint32_t type,
170                    GNUNET_DATACACHE_Iterator iter,
171                    void *iter_cls)
172 {
173   struct Plugin *plugin = cls;
174   sqlite3_stmt *stmt;
175   struct GNUNET_TIME_Absolute now;
176   struct GNUNET_TIME_Absolute exp;
177   unsigned int size;
178   const char *dat;
179   unsigned int cnt;
180   unsigned int off;
181   unsigned int total;
182   char scratch[256];
183
184   now = GNUNET_TIME_absolute_get ();
185 #if DEBUG_DATACACHE_SQLITE
186   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
187               "Processing `%s' for key `%4s'\n",
188               "GET",
189               GNUNET_h2s (key));
190 #endif
191   if (sq_prepare (plugin->dbh,
192                   "SELECT count(*) FROM ds090 WHERE key=? AND type=? AND expire >= ?",
193                   &stmt) != SQLITE_OK)
194     {
195       GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
196                   _("`%s' failed at %s:%d with error: %s\n"),
197                   "sq_prepare", __FILE__, __LINE__, 
198                   sqlite3_errmsg (plugin->dbh));
199       return 0;
200     }
201   sqlite3_bind_blob (stmt, 1, key, sizeof (GNUNET_HashCode),
202                      SQLITE_TRANSIENT);
203   sqlite3_bind_int (stmt, 2, type);
204   sqlite3_bind_int64 (stmt, 3, now.value);
205   if (SQLITE_ROW != sqlite3_step (stmt))
206     {
207       LOG_SQLITE (plugin->dbh,
208                   GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, 
209                   "sqlite_step");
210       sqlite3_finalize (stmt);
211       return 0;
212     }
213   total = sqlite3_column_int (stmt, 0);
214   sqlite3_finalize (stmt);
215   if ( (total == 0) || (iter == NULL) )
216     return total;    
217
218   cnt = 0;
219   off = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, total);
220   while (cnt < total)
221     {
222       off = (off + 1) % total;
223       GNUNET_snprintf (scratch, 
224                        sizeof(scratch),
225                        "SELECT value,expire FROM ds090 WHERE key=? AND type=? AND expire >= ? LIMIT 1 OFFSET %u",
226                        off);
227       if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
228         {
229           GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
230                       _("`%s' failed at %s:%d with error: %s\n"),
231                       "sq_prepare", __FILE__, __LINE__,
232                       sqlite3_errmsg (plugin->dbh));
233           return cnt;
234         }
235       sqlite3_bind_blob (stmt, 1, key, sizeof (GNUNET_HashCode),
236                          SQLITE_TRANSIENT);
237       sqlite3_bind_int (stmt, 2, type);
238       sqlite3_bind_int64 (stmt, 3, now.value);
239       if (sqlite3_step (stmt) != SQLITE_ROW)
240         break;
241       size = sqlite3_column_bytes (stmt, 0);
242       dat = sqlite3_column_blob (stmt, 0);
243       exp.value = sqlite3_column_int64 (stmt, 1);
244       cnt++;
245       if (GNUNET_OK != iter (iter_cls,
246                              exp,
247                              key, 
248                              size,
249                              dat,
250                              type))
251         {
252           sqlite3_finalize (stmt);
253           break;
254         }
255       sqlite3_finalize (stmt);
256     }
257   return cnt;
258 }
259
260
261 /**
262  * Delete the entry with the lowest expiration value
263  * from the datacache right now.
264  * 
265  * @param cls closure (our "struct Plugin")
266  * @return GNUNET_OK on success, GNUNET_SYSERR on error
267  */ 
268 static int 
269 sqlite_plugin_del (void *cls)
270 {
271   struct Plugin *plugin = cls;
272   unsigned int dsize;
273   unsigned int dtype;
274   sqlite3_stmt *stmt;
275   sqlite3_stmt *dstmt;
276
277 #if DEBUG_DATACACHE_SQLITE
278   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
279               "Processing `%s'\n",
280               "DEL");
281 #endif
282   stmt = NULL;
283   dstmt = NULL;
284   if ((sq_prepare (plugin->dbh,
285                    "SELECT type, key, value FROM ds090 ORDER BY expire ASC LIMIT 1",
286                    &stmt) != SQLITE_OK) ||
287       (sq_prepare (plugin->dbh,
288                    "DELETE FROM ds090 "
289                    "WHERE key=? AND value=? AND type=?",
290                    &dstmt) != SQLITE_OK))
291     {
292       GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
293                   _("`%s' failed at %s:%d with error: %s\n"),
294                   "sq_prepare", __FILE__, __LINE__, sqlite3_errmsg (plugin->dbh));
295       if (dstmt != NULL)
296         sqlite3_finalize (dstmt);
297       if (stmt != NULL)
298         sqlite3_finalize (stmt);
299       return GNUNET_SYSERR;
300     }
301   if (SQLITE_ROW != sqlite3_step (stmt))
302     {
303       GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
304                   _("`%s' failed at %s:%d with error: %s\n"),
305                   "sqlite3_step", __FILE__, __LINE__,
306                   sqlite3_errmsg (plugin->dbh));
307       sqlite3_finalize (dstmt);
308       sqlite3_finalize (stmt);
309       return GNUNET_SYSERR;
310     }
311   dtype = sqlite3_column_int (stmt, 0);
312   GNUNET_break (sqlite3_column_bytes (stmt, 1) == sizeof (GNUNET_HashCode));
313   dsize = sqlite3_column_bytes (stmt, 2);
314   sqlite3_bind_blob (dstmt,
315                      1, sqlite3_column_blob (stmt, 1),
316                      sizeof (GNUNET_HashCode),
317                      SQLITE_TRANSIENT);
318   sqlite3_bind_blob (dstmt,
319                      2, sqlite3_column_blob (stmt, 2),
320                      dsize,
321                      SQLITE_TRANSIENT);
322   sqlite3_bind_int (dstmt, 3, dtype);
323   if (sqlite3_step (dstmt) != SQLITE_DONE)
324     {
325       GNUNET_log (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
326                   _("`%s' failed at %s:%d with error: %s\n"),
327                   "sqlite3_step", __FILE__, __LINE__,
328                   sqlite3_errmsg (plugin->dbh));    
329       sqlite3_finalize (dstmt);
330       sqlite3_finalize (stmt);
331       return GNUNET_SYSERR;
332     }
333   plugin->env->delete_notify (plugin->env->cls,
334                               sqlite3_column_blob (stmt, 1),
335                               dsize + OVERHEAD);
336   sqlite3_finalize (dstmt);
337   sqlite3_finalize (stmt);
338   return GNUNET_OK;
339 }
340
341
342 /**
343  * Entry point for the plugin.
344  *
345  * @param cls closure (the "struct GNUNET_DATACACHE_PluginEnvironmnet")
346  * @return the plugin's closure (our "struct Plugin")
347  */
348 void *
349 libgnunet_plugin_datacache_sqlite_init (void *cls)
350 {
351   struct GNUNET_DATACACHE_PluginEnvironment *env = cls;
352   struct GNUNET_DATACACHE_PluginFunctions *api;
353   struct Plugin *plugin;
354   char *fn;
355   char *fn_utf8;
356   sqlite3 *dbh;
357   char *emsg;
358
359   fn = GNUNET_DISK_mktemp ("gnunet-datacache");
360   if (fn == NULL)
361     {
362       GNUNET_break (0);
363       return NULL;
364     }
365   fn_utf8 = GNUNET_STRINGS_to_utf8 (fn, strlen (fn),
366 #ifdef ENABLE_NLS
367                                     nl_langinfo (CODESET)
368 #else
369                                     "UTF-8"      /* good luck */
370 #endif
371     );
372   if (SQLITE_OK != sqlite3_open (fn_utf8, &dbh))
373     {
374       GNUNET_free (fn);
375       GNUNET_free (fn_utf8);
376       return NULL;
377     }
378   GNUNET_free (fn);
379
380   SQLITE3_EXEC (dbh, "PRAGMA temp_store=MEMORY");
381   SQLITE3_EXEC (dbh, "PRAGMA synchronous=OFF");
382   SQLITE3_EXEC (dbh, "PRAGMA count_changes=OFF");
383   SQLITE3_EXEC (dbh, "PRAGMA page_size=4092");
384   SQLITE3_EXEC (dbh,
385                 "CREATE TABLE ds090 ("
386                 "  type INTEGER NOT NULL DEFAULT 0,"
387                 "  expire INTEGER NOT NULL DEFAULT 0,"
388                 "  key BLOB NOT NULL DEFAULT '',"
389                 "  value BLOB NOT NULL DEFAULT '')");
390   SQLITE3_EXEC (dbh, "CREATE INDEX idx_hashidx ON ds090 (key,type,expire)");
391   plugin = GNUNET_malloc (sizeof (struct Plugin));
392   plugin->env = env;
393   plugin->dbh = dbh;
394   plugin->fn = fn_utf8;
395   api = GNUNET_malloc (sizeof (struct GNUNET_DATACACHE_PluginFunctions));
396   api->cls = plugin;
397   api->get = &sqlite_plugin_get;
398   api->put = &sqlite_plugin_put;
399   api->del = &sqlite_plugin_del;
400   GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
401                    "sqlite", _("Sqlite datacache running\n"));
402   return api;
403 }
404
405
406 /**
407  * Exit point from the plugin.
408  *
409  * @param cls closure (our "struct Plugin")
410  * @return NULL
411  */
412 void *
413 libgnunet_plugin_datacache_sqlite_done (void *cls)
414 {
415   struct GNUNET_DATACACHE_PluginFunctions *api = cls;
416   struct Plugin *plugin = api->cls;
417
418   if (0 != UNLINK (plugin->fn))
419     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
420                               "unlink", 
421                               plugin->fn);
422   GNUNET_free (plugin->fn);
423   sqlite3_close (plugin->dbh);
424   GNUNET_free (plugin);
425   GNUNET_free (api);
426   return NULL;
427 }
428
429
430
431 /* end of plugin_datacache_sqlite.c */
432