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__)
55 * Context for all functions in this plugin.
61 * Configuration handle
63 const struct GNUNET_CONFIGURATION_Handle *cfg;
71 * Native SQLite database handle.
76 * Precompiled SQL for inserting into peerstoredata
78 sqlite3_stmt *insert_peerstoredata;
81 * Precompiled SQL for selecting from peerstoredata
83 sqlite3_stmt *select_peerstoredata;
86 * Precompiled SQL for selecting from peerstoredata
88 sqlite3_stmt *select_peerstoredata_by_pid;
91 * Precompiled SQL for selecting from peerstoredata
93 sqlite3_stmt *select_peerstoredata_by_ss;
96 * Precompiled SQL for selecting from peerstoredata
98 sqlite3_stmt *select_peerstoredata_by_both;
103 * The given 'sqlite' statement has been prepared to be run.
104 * It will return a record which should be given to the iterator.
105 * Runs the statement and parses the returned record.
107 * @param plugin plugin context
108 * @param stmt to run (and then clean up)
109 * @param iter iterator to call with the result
110 * @param iter_cls closure for @a iter
111 * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
114 get_record_and_call_iterator (struct Plugin *plugin,
116 GNUNET_PEERSTORE_RecordIterator iter, void *iter_cls)
120 const struct GNUNET_PeerIdentity *pid;
121 const char *sub_system;
126 if (SQLITE_ROW == (sret = sqlite3_step (stmt)))
128 pid = sqlite3_column_blob(stmt, 0);
129 sub_system = (const char*) sqlite3_column_text(stmt, 1);
130 value = sqlite3_column_blob(stmt, 2);
131 value_size = sqlite3_column_bytes(stmt, 2);
133 iter (iter_cls, pid, sub_system, value, value_size);
138 if (SQLITE_DONE != sret)
139 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite_step");
141 if (SQLITE_OK != sqlite3_reset (stmt))
143 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
150 * Iterate over the records given an optional peer id
153 * @param cls closure (internal context for the plugin)
154 * @param peer Peer identity (can be NULL)
155 * @param sub_system name of sub system (can be NULL)
156 * @param iter function to call with the result
157 * @param iter_cls closure for @a iter
158 * @return #GNUNET_OK on success, #GNUNET_NO if there were no results, #GNUNET_SYSERR on error
161 peerstore_sqlite_iterate_records (void *cls,
162 const struct GNUNET_PeerIdentity *peer,
163 const char *sub_system,
164 GNUNET_PEERSTORE_RecordIterator iter, void *iter_cls)
166 struct Plugin *plugin = cls;
170 if(NULL == sub_system && NULL == peer)
171 stmt = plugin->select_peerstoredata;
172 else if(NULL == sub_system)
174 stmt = plugin->select_peerstoredata_by_pid;
175 err = (SQLITE_OK != sqlite3_bind_blob(stmt, 1, peer, sizeof(struct GNUNET_PeerIdentity), SQLITE_STATIC));
177 else if(NULL == peer)
179 stmt = plugin->select_peerstoredata_by_ss;
180 err = (SQLITE_OK != sqlite3_bind_text(stmt, 1, sub_system, strlen(sub_system) + 1, SQLITE_STATIC));
184 stmt = plugin->select_peerstoredata_by_both;
186 (SQLITE_OK != sqlite3_bind_blob(stmt, 1, peer, sizeof(struct GNUNET_PeerIdentity), SQLITE_STATIC))
187 || (SQLITE_OK != sqlite3_bind_text(stmt, 2, sub_system, strlen(sub_system) + 1, SQLITE_STATIC));
192 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
193 "sqlite3_bind_XXXX");
194 if (SQLITE_OK != sqlite3_reset (stmt))
196 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
198 return GNUNET_SYSERR;
200 return get_record_and_call_iterator (plugin, stmt, iter, iter_cls);
204 * Store a record in the peerstore.
205 * Key is the combination of sub system and peer identity.
206 * One key can store multiple values.
208 * @param cls closure (internal context for the plugin)
209 * @param peer peer identity
210 * @param sub_system name of the GNUnet sub system responsible
211 * @param value value to be stored
212 * @param size size of value to be stored
213 * @return #GNUNET_OK on success, else #GNUNET_SYSERR
216 peerstore_sqlite_store_record(void *cls,
217 const char *sub_system,
218 const struct GNUNET_PeerIdentity *peer,
223 struct Plugin *plugin = cls;
224 sqlite3_stmt *stmt = plugin->insert_peerstoredata;
226 //FIXME: check if value exists with the same key first
228 if(SQLITE_OK != sqlite3_bind_text(stmt, 1, sub_system, strlen(sub_system) + 1, SQLITE_STATIC)
229 || SQLITE_OK != sqlite3_bind_blob(stmt, 2, peer, sizeof(struct GNUNET_PeerIdentity), SQLITE_STATIC)
230 || SQLITE_OK != sqlite3_bind_text(stmt, 3, key, strlen(key) + 1, SQLITE_STATIC)
231 || SQLITE_OK != sqlite3_bind_blob(stmt, 4, value, size, SQLITE_STATIC))
232 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
234 else if (SQLITE_DONE != sqlite3_step (stmt))
236 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
239 if (SQLITE_OK != sqlite3_reset (stmt))
241 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
243 return GNUNET_SYSERR;
251 * @brief Prepare a SQL statement
253 * @param dbh handle to the database
254 * @param sql SQL statement, UTF-8 encoded
255 * @return 0 on success
258 sql_exec (sqlite3 *dbh, const char *sql)
262 result = sqlite3_exec (dbh, sql, NULL, NULL, NULL);
263 LOG (GNUNET_ERROR_TYPE_DEBUG,
264 "Executed `%s' / %d\n", sql, result);
265 if (result != SQLITE_OK)
266 LOG (GNUNET_ERROR_TYPE_ERROR,
267 _("Error executing SQL query: %s\n %s\n"),
268 sqlite3_errmsg (dbh), sql);
273 * @brief Prepare a SQL statement
275 * @param dbh handle to the database
276 * @param sql SQL statement, UTF-8 encoded
277 * @param stmt set to the prepared statement
278 * @return 0 on success
281 sql_prepare (sqlite3 *dbh, const char *sql, sqlite3_stmt **stmt)
286 result = sqlite3_prepare_v2 (dbh, sql, strlen (sql), stmt,
287 (const char **) &tail);
288 LOG (GNUNET_ERROR_TYPE_DEBUG,
289 "Prepared `%s' / %p: %d\n", sql, *stmt, result);
290 if (result != SQLITE_OK)
291 LOG (GNUNET_ERROR_TYPE_ERROR,
292 _("Error preparing SQL query: %s\n %s\n"),
293 sqlite3_errmsg (dbh), sql);
298 * Initialize the database connections and associated
299 * data structures (create tables and indices
300 * as needed as well).
302 * @param plugin the plugin context (state for this module)
303 * @return GNUNET_OK on success
306 database_setup (struct Plugin *plugin)
311 GNUNET_CONFIGURATION_get_value_filename (plugin->cfg, "peerstore-sqlite",
312 "FILENAME", &filename))
314 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
315 "peerstore-sqlite", "FILENAME");
316 return GNUNET_SYSERR;
318 if (GNUNET_OK != GNUNET_DISK_file_test (filename))
320 if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (filename))
323 GNUNET_free (filename);
324 return GNUNET_SYSERR;
327 /* filename should be UTF-8-encoded. If it isn't, it's a bug */
328 plugin->fn = filename;
330 /* Open database and precompile statements */
331 if (SQLITE_OK != sqlite3_open (plugin->fn, &plugin->dbh))
333 LOG (GNUNET_ERROR_TYPE_ERROR,
334 _("Unable to initialize SQLite: %s.\n"),
335 sqlite3_errmsg (plugin->dbh));
336 return GNUNET_SYSERR;
339 sql_exec (plugin->dbh, "PRAGMA temp_store=MEMORY");
340 sql_exec (plugin->dbh, "PRAGMA synchronous=NORMAL");
341 sql_exec (plugin->dbh, "PRAGMA legacy_file_format=OFF");
342 sql_exec (plugin->dbh, "PRAGMA auto_vacuum=INCREMENTAL");
343 sql_exec (plugin->dbh, "PRAGMA encoding=\"UTF-8\"");
344 sql_exec (plugin->dbh, "PRAGMA count_changes=OFF");
345 sql_exec (plugin->dbh, "PRAGMA page_size=4096");
347 sqlite3_busy_timeout (plugin->dbh, BUSY_TIMEOUT_MS);
351 sql_exec (plugin->dbh,
352 "CREATE TABLE IF NOT EXISTS peerstoredata (\n"
353 " sub_system TEXT NOT NULL,\n"
354 " peer_id BLOB NOT NULL,\n"
355 " key TEXT NOT NULL,\n"
359 /* Prepare statements */
361 sql_prepare (plugin->dbh,
362 "INSERT INTO peerstoredata (sub_system, peer_id, key, value) VALUES (?,?,?,?);",
363 &plugin->insert_peerstoredata);
364 sql_prepare(plugin->dbh,
365 "SELECT peer_id, sub_system, value FROM peerstoredata",
366 &plugin->select_peerstoredata);
367 sql_prepare(plugin->dbh,
368 "SELECT peer_id, sub_system, value FROM peerstoredata WHERE peer_id = ?",
369 &plugin->select_peerstoredata_by_pid);
370 sql_prepare(plugin->dbh,
371 "SELECT peer_id, sub_system, value FROM peerstoredata WHERE sub_system = ?",
372 &plugin->select_peerstoredata_by_ss);
373 sql_prepare(plugin->dbh,
374 "SELECT peer_id, sub_system, value FROM peerstoredata WHERE peer_id = ? AND sub_system = ?",
375 &plugin->select_peerstoredata_by_both);
381 * Shutdown database connection and associate data
383 * @param plugin the plugin context (state for this module)
386 database_shutdown (struct Plugin *plugin)
390 while (NULL != (stmt = sqlite3_next_stmt (plugin->dbh, NULL)))
392 result = sqlite3_finalize (stmt);
393 if (SQLITE_OK != result)
394 LOG (GNUNET_ERROR_TYPE_WARNING,
395 "Failed to close statement %p: %d\n", stmt, result);
397 if (SQLITE_OK != sqlite3_close (plugin->dbh))
398 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close");
400 GNUNET_free_non_null (plugin->fn);
404 * Entry point for the plugin.
406 * @param cls The struct GNUNET_CONFIGURATION_Handle.
407 * @return NULL on error, otherwise the plugin context
410 libgnunet_plugin_peerstore_sqlite_init (void *cls)
412 static struct Plugin plugin;
413 const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
414 struct GNUNET_PEERSTORE_PluginFunctions *api;
416 if (NULL != plugin.cfg)
417 return NULL; /* can only initialize once! */
418 memset (&plugin, 0, sizeof (struct Plugin));
420 if (GNUNET_OK != database_setup (&plugin))
422 database_shutdown (&plugin);
425 api = GNUNET_new (struct GNUNET_PEERSTORE_PluginFunctions);
427 api->store_record = &peerstore_sqlite_store_record;
428 api->iterate_records = &peerstore_sqlite_iterate_records;
429 LOG(GNUNET_ERROR_TYPE_DEBUG, "Sqlite plugin is running\n");
434 * Exit point from the plugin.
436 * @param cls The plugin context (as returned by "init")
437 * @return Always NULL
440 libgnunet_plugin_peerstore_sqlite_done (void *cls)
442 struct GNUNET_PEERSTORE_PluginFunctions *api = cls;
443 struct Plugin *plugin = api->cls;
445 database_shutdown (plugin);
448 LOG (GNUNET_ERROR_TYPE_DEBUG, "Sqlite plugin is finished\n");
453 /* end of plugin_peerstore_sqlite.c */