2 This file is part of GNUnet
3 (C) 2006, 2009 Christian Grothoff (and other contributing authors)
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.
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.
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.
22 * @file datacache/plugin_datacache_sqlite.c
23 * @brief sqlite for an implementation of a database backend for the datacache
24 * @author Christian Grothoff
27 #include "gnunet_util_lib.h"
28 #include "gnunet_datacache_plugin.h"
31 #define LOG(kind,...) GNUNET_log_from (kind, "datacache-sqlite", __VA_ARGS__)
33 #define LOG_STRERROR_FILE(kind,op,fn) GNUNET_log_from_strerror_file (kind, "datacache-sqlite", op, fn)
37 * How much overhead do we assume per entry in the
40 #define OVERHEAD (sizeof(struct GNUNET_HashCode) + 32)
43 * Context for all functions in this plugin.
48 * Our execution environment.
50 struct GNUNET_DATACACHE_PluginEnvironment *env;
53 * Handle to the sqlite database.
58 * Filename used for the DB.
65 * Log an error message at log-level 'level' that indicates
66 * a failure of the command 'cmd' on file 'filename'
67 * with the message given by strerror(errno).
69 #define LOG_SQLITE(db, level, cmd) do { LOG (level, _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, sqlite3_errmsg(db)); } while(0)
72 #define SQLITE3_EXEC(db, cmd) do { emsg = NULL; if (SQLITE_OK != sqlite3_exec(db, cmd, NULL, NULL, &emsg)) { 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)
76 * @brief Prepare a SQL statement
79 sq_prepare (sqlite3 * dbh, const char *zSql, /* SQL statement, UTF-8 encoded */
80 sqlite3_stmt ** ppStmt)
81 { /* OUT: Statement handle */
84 return sqlite3_prepare (dbh, zSql, strlen (zSql), ppStmt,
85 (const char **) &dummy);
90 * Store an item in the datastore.
92 * @param cls closure (our "struct Plugin")
93 * @param key key to store data under
94 * @param size number of bytes in data
95 * @param data data to store
96 * @param type type of the value
97 * @param discard_time when to discard the value in any case
98 * @param path_info_len number of entries in 'path_info'
99 * @param path_info array of peers that have processed the request
100 * @return 0 if duplicate, -1 on error, number of bytes used otherwise
103 sqlite_plugin_put (void *cls,
104 const struct GNUNET_HashCode *key,
105 size_t size, const char *data,
106 enum GNUNET_BLOCK_Type type,
107 struct GNUNET_TIME_Absolute discard_time,
108 unsigned int path_info_len,
109 const struct GNUNET_PeerIdentity *path_info)
111 struct Plugin *plugin = cls;
115 LOG (GNUNET_ERROR_TYPE_DEBUG,
116 "Processing `%s' of %u bytes with key `%4s' and expiration %s\n",
117 "PUT", (unsigned int) size, GNUNET_h2s (key),
118 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining (discard_time), GNUNET_YES));
119 dval = (int64_t) discard_time.abs_value;
124 "INSERT INTO ds090 (type, expire, key, value, path) VALUES (?, ?, ?, ?, ?)",
127 LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
131 if ((SQLITE_OK != sqlite3_bind_int (stmt, 1, type)) ||
132 (SQLITE_OK != sqlite3_bind_int64 (stmt, 2, dval)) ||
134 sqlite3_bind_blob (stmt, 3,
135 key, sizeof (struct GNUNET_HashCode),
136 SQLITE_TRANSIENT)) ||
137 (SQLITE_OK != sqlite3_bind_blob (stmt, 4,
139 SQLITE_TRANSIENT)) ||
140 (SQLITE_OK != sqlite3_bind_blob (stmt, 5,
142 path_info_len * sizeof (struct GNUNET_PeerIdentity),
145 LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
147 sqlite3_finalize (stmt);
150 if (SQLITE_DONE != sqlite3_step (stmt))
152 LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
154 sqlite3_finalize (stmt);
157 if (SQLITE_OK != sqlite3_finalize (stmt))
158 LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
160 return size + OVERHEAD;
165 * Iterate over the results for a particular key
168 * @param cls closure (our "struct Plugin")
170 * @param type entries of which type are relevant?
171 * @param iter maybe NULL (to just count)
172 * @param iter_cls closure for iter
173 * @return the number of results found
176 sqlite_plugin_get (void *cls, const struct GNUNET_HashCode * key,
177 enum GNUNET_BLOCK_Type type, GNUNET_DATACACHE_Iterator iter,
180 struct Plugin *plugin = cls;
182 struct GNUNET_TIME_Absolute now;
183 struct GNUNET_TIME_Absolute exp;
192 const struct GNUNET_PeerIdentity *path;
194 now = GNUNET_TIME_absolute_get ();
195 LOG (GNUNET_ERROR_TYPE_DEBUG, "Processing `%s' for key `%4s'\n", "GET",
199 "SELECT count(*) FROM ds090 WHERE key=? AND type=? AND expire >= ?",
202 LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
206 ntime = (int64_t) now.abs_value;
207 GNUNET_assert (ntime >= 0);
209 sqlite3_bind_blob (stmt, 1, key, sizeof (struct GNUNET_HashCode),
210 SQLITE_TRANSIENT)) ||
211 (SQLITE_OK != sqlite3_bind_int (stmt, 2, type)) ||
212 (SQLITE_OK != sqlite3_bind_int64 (stmt, 3, now.abs_value)))
214 LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
216 sqlite3_finalize (stmt);
220 if (SQLITE_ROW != sqlite3_step (stmt))
222 LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
224 sqlite3_finalize (stmt);
225 LOG (GNUNET_ERROR_TYPE_DEBUG,
226 "No content found when processing `%s' for key `%4s'\n", "GET",
230 total = sqlite3_column_int (stmt, 0);
231 sqlite3_finalize (stmt);
232 if ((total == 0) || (iter == NULL))
235 LOG (GNUNET_ERROR_TYPE_DEBUG,
236 "No content found when processing `%s' for key `%4s'\n", "GET",
242 off = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, total);
245 off = (off + 1) % total;
246 GNUNET_snprintf (scratch, sizeof (scratch),
247 "SELECT value,expire,path FROM ds090 WHERE key=? AND type=? AND expire >= ? LIMIT 1 OFFSET %u",
249 if (sq_prepare (plugin->dbh, scratch, &stmt) != SQLITE_OK)
251 LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
256 sqlite3_bind_blob (stmt, 1, key, sizeof (struct GNUNET_HashCode),
257 SQLITE_TRANSIENT)) ||
258 (SQLITE_OK != sqlite3_bind_int (stmt, 2, type)) ||
259 (SQLITE_OK != sqlite3_bind_int64 (stmt, 3, now.abs_value)))
261 LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
263 sqlite3_finalize (stmt);
266 if (sqlite3_step (stmt) != SQLITE_ROW)
268 size = sqlite3_column_bytes (stmt, 0);
269 dat = sqlite3_column_blob (stmt, 0);
270 exp.abs_value = sqlite3_column_int64 (stmt, 1);
271 psize = sqlite3_column_bytes (stmt, 2);
272 if (0 != psize % sizeof (struct GNUNET_PeerIdentity))
277 psize /= sizeof (struct GNUNET_PeerIdentity);
279 path = sqlite3_column_blob (stmt, 2);
282 ntime = (int64_t) exp.abs_value;
283 if (ntime == INT64_MAX)
284 exp = GNUNET_TIME_UNIT_FOREVER_ABS;
286 LOG (GNUNET_ERROR_TYPE_DEBUG,
287 "Found %u-byte result when processing `%s' for key `%4s'\n",
288 (unsigned int) size, "GET", GNUNET_h2s (key));
289 if (GNUNET_OK != iter (iter_cls, key, size, dat, type, exp, psize, path))
291 sqlite3_finalize (stmt);
294 sqlite3_finalize (stmt);
301 * Delete the entry with the lowest expiration value
302 * from the datacache right now.
304 * @param cls closure (our "struct Plugin")
305 * @return GNUNET_OK on success, GNUNET_SYSERR on error
308 sqlite_plugin_del (void *cls)
310 struct Plugin *plugin = cls;
311 unsigned long long rowid;
315 struct GNUNET_HashCode hc;
317 LOG (GNUNET_ERROR_TYPE_DEBUG, "Processing `%s'\n", "DEL");
322 "SELECT _ROWID_,key,value FROM ds090 ORDER BY expire ASC LIMIT 1",
325 LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
328 (void) sqlite3_finalize (stmt);
329 return GNUNET_SYSERR;
331 if (SQLITE_ROW != sqlite3_step (stmt))
333 LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
335 (void) sqlite3_finalize (stmt);
336 return GNUNET_SYSERR;
338 rowid = sqlite3_column_int64 (stmt, 0);
339 GNUNET_assert (sqlite3_column_bytes (stmt, 1) == sizeof (struct GNUNET_HashCode));
340 memcpy (&hc, sqlite3_column_blob (stmt, 1), sizeof (struct GNUNET_HashCode));
341 dsize = sqlite3_column_bytes (stmt, 2);
342 if (SQLITE_OK != sqlite3_finalize (stmt))
343 LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
345 if (sq_prepare (plugin->dbh, "DELETE FROM ds090 WHERE _ROWID_=?", &dstmt) !=
348 LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
351 (void) sqlite3_finalize (stmt);
352 return GNUNET_SYSERR;
354 if (SQLITE_OK != sqlite3_bind_int64 (dstmt, 1, rowid))
356 LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
358 (void) sqlite3_finalize (dstmt);
359 return GNUNET_SYSERR;
361 if (sqlite3_step (dstmt) != SQLITE_DONE)
363 LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
365 (void) sqlite3_finalize (dstmt);
366 return GNUNET_SYSERR;
368 plugin->env->delete_notify (plugin->env->cls, &hc, dsize + OVERHEAD);
369 if (SQLITE_OK != sqlite3_finalize (dstmt))
370 LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
377 * Entry point for the plugin.
379 * @param cls closure (the "struct GNUNET_DATACACHE_PluginEnvironmnet")
380 * @return the plugin's closure (our "struct Plugin")
383 libgnunet_plugin_datacache_sqlite_init (void *cls)
385 struct GNUNET_DATACACHE_PluginEnvironment *env = cls;
386 struct GNUNET_DATACACHE_PluginFunctions *api;
387 struct Plugin *plugin;
394 GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
398 if (SQLITE_OK != sqlite3_open (":memory:", &dbh))
404 fn = GNUNET_DISK_mktemp ("gnunet-datacache");
410 /* fn should be UTF-8-encoded. If it isn't, it's a bug. */
411 fn_utf8 = GNUNET_strdup (fn);
412 if (SQLITE_OK != sqlite3_open (fn_utf8, &dbh))
415 GNUNET_free (fn_utf8);
421 SQLITE3_EXEC (dbh, "PRAGMA temp_store=MEMORY");
422 SQLITE3_EXEC (dbh, "PRAGMA locking_mode=EXCLUSIVE");
423 SQLITE3_EXEC (dbh, "PRAGMA journal_mode=OFF");
424 SQLITE3_EXEC (dbh, "PRAGMA synchronous=OFF");
425 SQLITE3_EXEC (dbh, "PRAGMA count_changes=OFF");
426 SQLITE3_EXEC (dbh, "PRAGMA page_size=4092");
428 GNUNET_CONFIGURATION_get_value_yesno (env->cfg,
431 SQLITE3_EXEC (dbh, "PRAGMA sqlite_temp_store=3");
434 "CREATE TABLE ds090 (" " type INTEGER NOT NULL DEFAULT 0,"
435 " expire INTEGER NOT NULL DEFAULT 0,"
436 " key BLOB NOT NULL DEFAULT '',"
437 " value BLOB NOT NULL DEFAULT '',"
438 " path BLOB DEFAULT '')");
439 SQLITE3_EXEC (dbh, "CREATE INDEX idx_hashidx ON ds090 (key,type,expire)");
440 SQLITE3_EXEC (dbh, "CREATE INDEX idx_expire ON ds090 (expire)");
441 plugin = GNUNET_malloc (sizeof (struct Plugin));
444 plugin->fn = fn_utf8;
445 api = GNUNET_malloc (sizeof (struct GNUNET_DATACACHE_PluginFunctions));
447 api->get = &sqlite_plugin_get;
448 api->put = &sqlite_plugin_put;
449 api->del = &sqlite_plugin_del;
450 LOG (GNUNET_ERROR_TYPE_INFO, _("Sqlite datacache running\n"));
456 * Exit point from the plugin.
458 * @param cls closure (our "struct Plugin")
462 libgnunet_plugin_datacache_sqlite_done (void *cls)
464 struct GNUNET_DATACACHE_PluginFunctions *api = cls;
465 struct Plugin *plugin = api->cls;
468 #if SQLITE_VERSION_NUMBER >= 3007000
472 #if !WINDOWS || defined(__CYGWIN__)
473 if ( (NULL != plugin->fn) &&
474 (0 != UNLINK (plugin->fn)) )
475 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", plugin->fn);
476 GNUNET_free_non_null (plugin->fn);
478 result = sqlite3_close (plugin->dbh);
479 #if SQLITE_VERSION_NUMBER >= 3007000
480 if (result == SQLITE_BUSY)
482 LOG (GNUNET_ERROR_TYPE_WARNING,
484 ("Tried to close sqlite without finalizing all prepared statements.\n"));
485 stmt = sqlite3_next_stmt (plugin->dbh, NULL);
488 LOG (GNUNET_ERROR_TYPE_DEBUG, "Closing statement %p\n", stmt);
489 result = sqlite3_finalize (stmt);
490 if (result != SQLITE_OK)
491 LOG (GNUNET_ERROR_TYPE_WARNING, _("Failed to close statement %p: %d\n"),
493 stmt = sqlite3_next_stmt (plugin->dbh, NULL);
495 result = sqlite3_close (plugin->dbh);
498 if (SQLITE_OK != result)
499 LOG_SQLITE (plugin->dbh, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close");
501 #if WINDOWS && !defined(__CYGWIN__)
502 if ( (NULL != plugin->fn) &&
503 (0 != UNLINK (plugin->fn)) )
504 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", plugin->fn);
505 GNUNET_free_non_null (plugin->fn);
507 GNUNET_free (plugin);
514 /* end of plugin_datacache_sqlite.c */