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_key;
96 * Precompiled SQL for selecting from peerstoredata
98 sqlite3_stmt *select_peerstoredata_by_all;
103 * Iterate over the records given an optional peer id
106 * @param cls closure (internal context for the plugin)
107 * @param sub_system name of sub system
108 * @param peer Peer identity (can be NULL)
109 * @param key entry key string (can be NULL)
110 * @param iter function to call with the result
111 * @param iter_cls closure for @a iter
112 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
115 peerstore_sqlite_iterate_records (void *cls,
116 const char *sub_system,
117 const struct GNUNET_PeerIdentity *peer,
119 GNUNET_PEERSTORE_RecordIterator iter, void *iter_cls)
121 struct Plugin *plugin = cls;
125 const char *ret_sub_system;
126 const struct GNUNET_PeerIdentity *ret_peer;
128 const void *ret_value;
129 size_t ret_value_size;
131 if(NULL == peer && NULL == key)
133 stmt = plugin->select_peerstoredata;
134 err = (SQLITE_OK != sqlite3_bind_text(stmt, 1, sub_system, strlen(sub_system) + 1, SQLITE_STATIC));
138 stmt = plugin->select_peerstoredata_by_pid;
139 err = (SQLITE_OK != sqlite3_bind_text(stmt, 1, sub_system, strlen(sub_system) + 1, SQLITE_STATIC))
140 || (SQLITE_OK != sqlite3_bind_blob(stmt, 2, peer, sizeof(struct GNUNET_PeerIdentity), SQLITE_STATIC));
142 else if(NULL == peer)
144 stmt = plugin->select_peerstoredata_by_key;
145 err = (SQLITE_OK != sqlite3_bind_text(stmt, 1, sub_system, strlen(sub_system) + 1, SQLITE_STATIC))
146 || (SQLITE_OK != sqlite3_bind_text(stmt, 3, key, strlen(key) + 1, SQLITE_STATIC));
150 stmt = plugin->select_peerstoredata_by_all;
151 err = (SQLITE_OK != sqlite3_bind_text(stmt, 1, sub_system, strlen(sub_system) + 1, SQLITE_STATIC))
152 || (SQLITE_OK != sqlite3_bind_blob(stmt, 2, peer, sizeof(struct GNUNET_PeerIdentity), SQLITE_STATIC))
153 || (SQLITE_OK != sqlite3_bind_text(stmt, 3, key, strlen(key) + 1, SQLITE_STATIC));
158 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
159 "sqlite3_bind_XXXX");
160 if (SQLITE_OK != sqlite3_reset (stmt))
162 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
164 return GNUNET_SYSERR;
166 while (SQLITE_ROW == (sret = sqlite3_step (stmt)))
168 ret_sub_system = (const char *)sqlite3_column_text(stmt, 0);
169 ret_peer = sqlite3_column_blob(stmt, 1);
170 ret_key = (const char *)sqlite3_column_text(stmt, 2);
171 ret_value = sqlite3_column_blob(stmt, 3);
172 ret_value_size = sqlite3_column_bytes(stmt, 3);
174 iter (iter_cls, ret_sub_system, ret_peer, ret_key, ret_value, ret_value_size);
176 if (SQLITE_DONE != sret)
178 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite_step");
181 if (SQLITE_OK != sqlite3_reset (stmt))
184 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
189 return GNUNET_SYSERR;
194 * Store a record in the peerstore.
195 * Key is the combination of sub system and peer identity.
196 * One key can store multiple values.
198 * @param cls closure (internal context for the plugin)
199 * @param peer peer identity
200 * @param sub_system name of the GNUnet sub system responsible
201 * @param value value to be stored
202 * @param size size of value to be stored
203 * @return #GNUNET_OK on success, else #GNUNET_SYSERR
206 peerstore_sqlite_store_record(void *cls,
207 const char *sub_system,
208 const struct GNUNET_PeerIdentity *peer,
213 struct Plugin *plugin = cls;
214 sqlite3_stmt *stmt = plugin->insert_peerstoredata;
216 //FIXME: check if value exists with the same key first
218 if(SQLITE_OK != sqlite3_bind_text(stmt, 1, sub_system, strlen(sub_system) + 1, SQLITE_STATIC)
219 || SQLITE_OK != sqlite3_bind_blob(stmt, 2, peer, sizeof(struct GNUNET_PeerIdentity), SQLITE_STATIC)
220 || SQLITE_OK != sqlite3_bind_text(stmt, 3, key, strlen(key) + 1, SQLITE_STATIC)
221 || SQLITE_OK != sqlite3_bind_blob(stmt, 4, value, size, SQLITE_STATIC))
222 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
224 else if (SQLITE_DONE != sqlite3_step (stmt))
226 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
229 if (SQLITE_OK != sqlite3_reset (stmt))
231 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
233 return GNUNET_SYSERR;
241 * @brief Prepare a SQL statement
243 * @param dbh handle to the database
244 * @param sql SQL statement, UTF-8 encoded
245 * @return 0 on success
248 sql_exec (sqlite3 *dbh, const char *sql)
252 result = sqlite3_exec (dbh, sql, NULL, NULL, NULL);
253 LOG (GNUNET_ERROR_TYPE_DEBUG,
254 "Executed `%s' / %d\n", sql, result);
255 if (result != SQLITE_OK)
256 LOG (GNUNET_ERROR_TYPE_ERROR,
257 _("Error executing SQL query: %s\n %s\n"),
258 sqlite3_errmsg (dbh), sql);
263 * @brief Prepare a SQL statement
265 * @param dbh handle to the database
266 * @param sql SQL statement, UTF-8 encoded
267 * @param stmt set to the prepared statement
268 * @return 0 on success
271 sql_prepare (sqlite3 *dbh, const char *sql, sqlite3_stmt **stmt)
276 result = sqlite3_prepare_v2 (dbh, sql, strlen (sql), stmt,
277 (const char **) &tail);
278 LOG (GNUNET_ERROR_TYPE_DEBUG,
279 "Prepared `%s' / %p: %d\n", sql, *stmt, result);
280 if (result != SQLITE_OK)
281 LOG (GNUNET_ERROR_TYPE_ERROR,
282 _("Error preparing SQL query: %s\n %s\n"),
283 sqlite3_errmsg (dbh), sql);
288 * Initialize the database connections and associated
289 * data structures (create tables and indices
290 * as needed as well).
292 * @param plugin the plugin context (state for this module)
293 * @return GNUNET_OK on success
296 database_setup (struct Plugin *plugin)
301 GNUNET_CONFIGURATION_get_value_filename (plugin->cfg, "peerstore-sqlite",
302 "FILENAME", &filename))
304 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
305 "peerstore-sqlite", "FILENAME");
306 return GNUNET_SYSERR;
308 if (GNUNET_OK != GNUNET_DISK_file_test (filename))
310 if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (filename))
313 GNUNET_free (filename);
314 return GNUNET_SYSERR;
317 /* filename should be UTF-8-encoded. If it isn't, it's a bug */
318 plugin->fn = filename;
320 /* Open database and precompile statements */
321 if (SQLITE_OK != sqlite3_open (plugin->fn, &plugin->dbh))
323 LOG (GNUNET_ERROR_TYPE_ERROR,
324 _("Unable to initialize SQLite: %s.\n"),
325 sqlite3_errmsg (plugin->dbh));
326 return GNUNET_SYSERR;
329 sql_exec (plugin->dbh, "PRAGMA temp_store=MEMORY");
330 sql_exec (plugin->dbh, "PRAGMA synchronous=NORMAL");
331 sql_exec (plugin->dbh, "PRAGMA legacy_file_format=OFF");
332 sql_exec (plugin->dbh, "PRAGMA auto_vacuum=INCREMENTAL");
333 sql_exec (plugin->dbh, "PRAGMA encoding=\"UTF-8\"");
334 sql_exec (plugin->dbh, "PRAGMA count_changes=OFF");
335 sql_exec (plugin->dbh, "PRAGMA page_size=4096");
337 sqlite3_busy_timeout (plugin->dbh, BUSY_TIMEOUT_MS);
341 sql_exec (plugin->dbh,
342 "CREATE TABLE IF NOT EXISTS peerstoredata (\n"
343 " sub_system TEXT NOT NULL,\n"
344 " peer_id BLOB NOT NULL,\n"
345 " key TEXT NOT NULL,\n"
349 /* Prepare statements */
351 sql_prepare (plugin->dbh,
352 "INSERT INTO peerstoredata (sub_system, peer_id, key, value) VALUES (?,?,?,?);",
353 &plugin->insert_peerstoredata);
354 sql_prepare(plugin->dbh,
355 "SELECT peer_id, sub_system, value FROM peerstoredata"
356 " WHERE sub_system = ?",
357 &plugin->select_peerstoredata);
358 sql_prepare(plugin->dbh,
359 "SELECT peer_id, sub_system, value FROM peerstoredata"
360 " WHERE sub_system = ?"
362 &plugin->select_peerstoredata_by_pid);
363 sql_prepare(plugin->dbh,
364 "SELECT peer_id, sub_system, value FROM peerstoredata"
365 " WHERE sub_system = ?"
367 &plugin->select_peerstoredata_by_key);
368 sql_prepare(plugin->dbh,
369 "SELECT peer_id, sub_system, value FROM peerstoredata"
370 " WHERE sub_system = ?"
373 &plugin->select_peerstoredata_by_all);
379 * Shutdown database connection and associate data
381 * @param plugin the plugin context (state for this module)
384 database_shutdown (struct Plugin *plugin)
388 while (NULL != (stmt = sqlite3_next_stmt (plugin->dbh, NULL)))
390 result = sqlite3_finalize (stmt);
391 if (SQLITE_OK != result)
392 LOG (GNUNET_ERROR_TYPE_WARNING,
393 "Failed to close statement %p: %d\n", stmt, result);
395 if (SQLITE_OK != sqlite3_close (plugin->dbh))
396 LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close");
398 GNUNET_free_non_null (plugin->fn);
402 * Entry point for the plugin.
404 * @param cls The struct GNUNET_CONFIGURATION_Handle.
405 * @return NULL on error, otherwise the plugin context
408 libgnunet_plugin_peerstore_sqlite_init (void *cls)
410 static struct Plugin plugin;
411 const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
412 struct GNUNET_PEERSTORE_PluginFunctions *api;
414 if (NULL != plugin.cfg)
415 return NULL; /* can only initialize once! */
416 memset (&plugin, 0, sizeof (struct Plugin));
418 if (GNUNET_OK != database_setup (&plugin))
420 database_shutdown (&plugin);
423 api = GNUNET_new (struct GNUNET_PEERSTORE_PluginFunctions);
425 api->store_record = &peerstore_sqlite_store_record;
426 api->iterate_records = &peerstore_sqlite_iterate_records;
427 LOG(GNUNET_ERROR_TYPE_DEBUG, "Sqlite plugin is running\n");
432 * Exit point from the plugin.
434 * @param cls The plugin context (as returned by "init")
435 * @return Always NULL
438 libgnunet_plugin_peerstore_sqlite_done (void *cls)
440 struct GNUNET_PEERSTORE_PluginFunctions *api = cls;
441 struct Plugin *plugin = api->cls;
443 database_shutdown (plugin);
446 LOG (GNUNET_ERROR_TYPE_DEBUG, "Sqlite plugin is finished\n");
451 /* end of plugin_peerstore_sqlite.c */