2 * This file is part of GNUnet
3 * (C) 2013 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 peerstore/plugin_peerstore_sqlite.c
23 * @brief sqlite-based peerstore backend
24 * @author Omar Tarabai
28 #include "gnunet_peerstore_plugin.h"
29 #include "gnunet_peerstore_service.h"
30 #include "peerstore.h"
34 * After how many ms "busy" should a DB operation fail for good? A
35 * low value makes sure that we are more responsive to requests
36 * (especially PUTs). A high value guarantees a higher success rate
37 * (SELECTs in iterate can take several seconds despite LIMIT=1).
39 * The default value of 1s should ensure that users do not experience
40 * huge latencies while at the same time allowing operations to
41 * succeed with reasonable probability.
43 #define BUSY_TIMEOUT_MS 1000
46 * Log an error message at log-level 'level' that indicates
47 * a failure of the command 'cmd' on file 'filename'
48 * with the message given by strerror(errno).
50 #define LOG_SQLITE(db, level, cmd) do { GNUNET_log_from (level, "peerstore-sqlite", _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, sqlite3_errmsg(db->dbh)); } while(0)
52 #define LOG(kind,...) GNUNET_log_from (kind, "peerstore-sqlite", __VA_ARGS__)
57 * Context for all functions in this plugin.
63 * Configuration handle
65 const struct GNUNET_CONFIGURATION_Handle *cfg;
73 * Native SQLite database handle.
78 * Precompiled SQL for inserting into peerstoredata
80 sqlite3_stmt *insert_peerstoredata;
83 * Precompiled SQL for selecting from peerstoredata
85 sqlite3_stmt *select_peerstoredata;
88 * Precompiled SQL for selecting from peerstoredata
90 sqlite3_stmt *select_peerstoredata_by_pid;
93 * Precompiled SQL for selecting from peerstoredata
95 sqlite3_stmt *select_peerstoredata_by_key;
98 * Precompiled SQL for selecting from peerstoredata
100 sqlite3_stmt *select_peerstoredata_by_all;
103 * Precompiled SQL for deleting expired records from peerstoredata
105 sqlite3_stmt *expire_peerstoredata;
110 * Delete expired records (expiry < now)
112 * @param cls closure (internal context for the plugin)
113 * @param now time to use as reference
114 * @return number of records deleted
117 peerstore_sqlite_expire_records(void *cls,
118 struct GNUNET_TIME_Absolute now)
120 struct Plugin *plugin = cls;
121 sqlite3_stmt *stmt = plugin->expire_peerstoredata;
123 if(SQLITE_OK != sqlite3_bind_int64(stmt, 1, (sqlite3_int64)now.abs_value_us))
125 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_bind");
127 else if (SQLITE_DONE != sqlite3_step (stmt))
129 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
132 if (SQLITE_OK != sqlite3_reset (stmt))
134 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
138 return sqlite3_changes(plugin->dbh);
143 * Iterate over the records given an optional peer id
146 * @param cls closure (internal context for the plugin)
147 * @param sub_system name of sub system
148 * @param peer Peer identity (can be NULL)
149 * @param key entry key string (can be NULL)
150 * @param iter function to call with the result
151 * @param iter_cls closure for @a iter
152 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
155 peerstore_sqlite_iterate_records (void *cls,
156 const char *sub_system,
157 const struct GNUNET_PeerIdentity *peer,
159 GNUNET_PEERSTORE_Processor iter, void *iter_cls)
161 struct Plugin *plugin = cls;
165 struct GNUNET_PEERSTORE_Record *ret;
167 LOG(GNUNET_ERROR_TYPE_DEBUG, "Executing iterate request on sqlite db.\n");
168 if(NULL == peer && NULL == key)
170 stmt = plugin->select_peerstoredata;
171 err = (SQLITE_OK != sqlite3_bind_text(stmt, 1, sub_system, strlen(sub_system) + 1, SQLITE_STATIC));
175 stmt = plugin->select_peerstoredata_by_pid;
176 err = (SQLITE_OK != sqlite3_bind_text(stmt, 1, sub_system, strlen(sub_system) + 1, SQLITE_STATIC))
177 || (SQLITE_OK != sqlite3_bind_blob(stmt, 2, peer, sizeof(struct GNUNET_PeerIdentity), SQLITE_STATIC));
179 else if(NULL == peer)
181 stmt = plugin->select_peerstoredata_by_key;
182 err = (SQLITE_OK != sqlite3_bind_text(stmt, 1, sub_system, strlen(sub_system) + 1, SQLITE_STATIC))
183 || (SQLITE_OK != sqlite3_bind_text(stmt, 3, key, strlen(key) + 1, SQLITE_STATIC));
187 stmt = plugin->select_peerstoredata_by_all;
188 err = (SQLITE_OK != sqlite3_bind_text(stmt, 1, sub_system, strlen(sub_system) + 1, SQLITE_STATIC))
189 || (SQLITE_OK != sqlite3_bind_blob(stmt, 2, peer, sizeof(struct GNUNET_PeerIdentity), SQLITE_STATIC))
190 || (SQLITE_OK != sqlite3_bind_text(stmt, 3, key, strlen(key) + 1, SQLITE_STATIC));
195 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
196 "sqlite3_bind_XXXX");
197 if (SQLITE_OK != sqlite3_reset (stmt))
199 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
201 return GNUNET_SYSERR;
203 while (SQLITE_ROW == (sret = sqlite3_step (stmt)))
205 LOG(GNUNET_ERROR_TYPE_DEBUG, "Returning a matched record.\n");
206 ret = GNUNET_new(struct GNUNET_PEERSTORE_Record);
207 ret->sub_system = (char *)sqlite3_column_text(stmt, 0);
208 ret->peer = (struct GNUNET_PeerIdentity *)sqlite3_column_blob(stmt, 1);
209 ret->key = (char *)sqlite3_column_text(stmt, 2);
210 ret->value = (void *)sqlite3_column_blob(stmt, 3);
211 ret->value_size = sqlite3_column_bytes(stmt, 3);
212 ret->expiry = GNUNET_new(struct GNUNET_TIME_Absolute);
213 ret->expiry->abs_value_us = (uint64_t)sqlite3_column_int64(stmt, 4);
219 if (SQLITE_DONE != sret)
221 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite_step");
224 if (SQLITE_OK != sqlite3_reset (stmt))
227 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
232 return GNUNET_SYSERR;
237 * Store a record in the peerstore.
238 * Key is the combination of sub system and peer identity.
239 * One key can store multiple values.
241 * @param cls closure (internal context for the plugin)
242 * @param peer peer identity
243 * @param sub_system name of the GNUnet sub system responsible
244 * @param value value to be stored
245 * @param size size of value to be stored
246 * @return #GNUNET_OK on success, else #GNUNET_SYSERR
249 peerstore_sqlite_store_record(void *cls,
250 const char *sub_system,
251 const struct GNUNET_PeerIdentity *peer,
255 struct GNUNET_TIME_Absolute expiry)
257 struct Plugin *plugin = cls;
258 sqlite3_stmt *stmt = plugin->insert_peerstoredata;
260 if(SQLITE_OK != sqlite3_bind_text(stmt, 1, sub_system, strlen(sub_system) + 1, SQLITE_STATIC)
261 || SQLITE_OK != sqlite3_bind_blob(stmt, 2, peer, sizeof(struct GNUNET_PeerIdentity), SQLITE_STATIC)
262 || SQLITE_OK != sqlite3_bind_text(stmt, 3, key, strlen(key) + 1, SQLITE_STATIC)
263 || SQLITE_OK != sqlite3_bind_blob(stmt, 4, value, size, SQLITE_STATIC)
264 || SQLITE_OK != sqlite3_bind_int64(stmt, 5, (sqlite3_int64)expiry.abs_value_us))
265 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
267 else if (SQLITE_DONE != sqlite3_step (stmt))
269 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
272 if (SQLITE_OK != sqlite3_reset (stmt))
274 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
276 return GNUNET_SYSERR;
284 * @brief Prepare a SQL statement
286 * @param dbh handle to the database
287 * @param sql SQL statement, UTF-8 encoded
288 * @return 0 on success
291 sql_exec (sqlite3 *dbh, const char *sql)
295 result = sqlite3_exec (dbh, sql, NULL, NULL, NULL);
296 LOG (GNUNET_ERROR_TYPE_DEBUG,
297 "Executed `%s' / %d\n", sql, result);
298 if (result != SQLITE_OK)
299 LOG (GNUNET_ERROR_TYPE_ERROR,
300 _("Error executing SQL query: %s\n %s\n"),
301 sqlite3_errmsg (dbh), sql);
306 * @brief Prepare a SQL statement
308 * @param dbh handle to the database
309 * @param sql SQL statement, UTF-8 encoded
310 * @param stmt set to the prepared statement
311 * @return 0 on success
314 sql_prepare (sqlite3 *dbh, const char *sql, sqlite3_stmt **stmt)
319 result = sqlite3_prepare_v2 (dbh, sql, strlen (sql), stmt,
320 (const char **) &tail);
321 LOG (GNUNET_ERROR_TYPE_DEBUG,
322 "Prepared `%s' / %p: %d\n", sql, *stmt, result);
323 if (result != SQLITE_OK)
324 LOG (GNUNET_ERROR_TYPE_ERROR,
325 _("Error preparing SQL query: %s\n %s\n"),
326 sqlite3_errmsg (dbh), sql);
331 * Initialize the database connections and associated
332 * data structures (create tables and indices
333 * as needed as well).
335 * @param plugin the plugin context (state for this module)
336 * @return GNUNET_OK on success
339 database_setup (struct Plugin *plugin)
344 GNUNET_CONFIGURATION_get_value_filename (plugin->cfg, "peerstore-sqlite",
345 "FILENAME", &filename))
347 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
348 "peerstore-sqlite", "FILENAME");
349 return GNUNET_SYSERR;
351 if (GNUNET_OK != GNUNET_DISK_file_test (filename))
353 if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (filename))
356 GNUNET_free (filename);
357 return GNUNET_SYSERR;
360 /* filename should be UTF-8-encoded. If it isn't, it's a bug */
361 plugin->fn = filename;
363 /* Open database and precompile statements */
364 if (SQLITE_OK != sqlite3_open (plugin->fn, &plugin->dbh))
366 LOG (GNUNET_ERROR_TYPE_ERROR,
367 _("Unable to initialize SQLite: %s.\n"),
368 sqlite3_errmsg (plugin->dbh));
369 return GNUNET_SYSERR;
372 sql_exec (plugin->dbh, "PRAGMA temp_store=MEMORY");
373 sql_exec (plugin->dbh, "PRAGMA synchronous=NORMAL");
374 sql_exec (plugin->dbh, "PRAGMA legacy_file_format=OFF");
375 sql_exec (plugin->dbh, "PRAGMA auto_vacuum=INCREMENTAL");
376 sql_exec (plugin->dbh, "PRAGMA encoding=\"UTF-8\"");
377 sql_exec (plugin->dbh, "PRAGMA count_changes=OFF");
378 sql_exec (plugin->dbh, "PRAGMA page_size=4096");
380 sqlite3_busy_timeout (plugin->dbh, BUSY_TIMEOUT_MS);
384 sql_exec (plugin->dbh,
385 "CREATE TABLE IF NOT EXISTS peerstoredata (\n"
386 " sub_system TEXT NOT NULL,\n"
387 " peer_id BLOB NOT NULL,\n"
388 " key TEXT NOT NULL,\n"
389 " value BLOB NULL,\n"
390 " expiry INTEGER NOT NULL"
393 /* Prepare statements */
395 sql_prepare (plugin->dbh,
396 "INSERT INTO peerstoredata (sub_system, peer_id, key, value, expiry) VALUES (?,?,?,?,?);",
397 &plugin->insert_peerstoredata);
398 sql_prepare(plugin->dbh,
399 "SELECT * FROM peerstoredata"
400 " WHERE sub_system = ?",
401 &plugin->select_peerstoredata);
402 sql_prepare(plugin->dbh,
403 "SELECT * FROM peerstoredata"
404 " WHERE sub_system = ?"
406 &plugin->select_peerstoredata_by_pid);
407 sql_prepare(plugin->dbh,
408 "SELECT * FROM peerstoredata"
409 " WHERE sub_system = ?"
411 &plugin->select_peerstoredata_by_key);
412 sql_prepare(plugin->dbh,
413 "SELECT * FROM peerstoredata"
414 " WHERE sub_system = ?"
417 &plugin->select_peerstoredata_by_all);
418 sql_prepare(plugin->dbh,
419 "DELETE FROM peerstoredata"
421 &plugin->expire_peerstoredata);
427 * Shutdown database connection and associate data
429 * @param plugin the plugin context (state for this module)
432 database_shutdown (struct Plugin *plugin)
436 while (NULL != (stmt = sqlite3_next_stmt (plugin->dbh, NULL)))
438 result = sqlite3_finalize (stmt);
439 if (SQLITE_OK != result)
440 LOG (GNUNET_ERROR_TYPE_WARNING,
441 "Failed to close statement %p: %d\n", stmt, result);
443 if (SQLITE_OK != sqlite3_close (plugin->dbh))
444 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close");
446 GNUNET_free_non_null (plugin->fn);
450 * Entry point for the plugin.
452 * @param cls The struct GNUNET_CONFIGURATION_Handle.
453 * @return NULL on error, otherwise the plugin context
456 libgnunet_plugin_peerstore_sqlite_init (void *cls)
458 static struct Plugin plugin;
459 const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
460 struct GNUNET_PEERSTORE_PluginFunctions *api;
462 if (NULL != plugin.cfg)
463 return NULL; /* can only initialize once! */
464 memset (&plugin, 0, sizeof (struct Plugin));
466 if (GNUNET_OK != database_setup (&plugin))
468 database_shutdown (&plugin);
471 api = GNUNET_new (struct GNUNET_PEERSTORE_PluginFunctions);
473 api->store_record = &peerstore_sqlite_store_record;
474 api->iterate_records = &peerstore_sqlite_iterate_records;
475 api->expire_records = &peerstore_sqlite_expire_records;
476 LOG(GNUNET_ERROR_TYPE_DEBUG, "Sqlite plugin is running\n");
481 * Exit point from the plugin.
483 * @param cls The plugin context (as returned by "init")
484 * @return Always NULL
487 libgnunet_plugin_peerstore_sqlite_done (void *cls)
489 struct GNUNET_PEERSTORE_PluginFunctions *api = cls;
490 struct Plugin *plugin = api->cls;
492 database_shutdown (plugin);
495 LOG (GNUNET_ERROR_TYPE_DEBUG, "Sqlite plugin is finished\n");
500 /* end of plugin_peerstore_sqlite.c */