2 * This file is part of GNUnet
3 * Copyright (C) 2013, 2017 GNUnet e.V.
5 * GNUnet is free software: you can redistribute it and/or modify it
6 * under the terms of the GNU Affero General Public License as published
7 * by the Free Software Foundation, either version 3 of the License,
8 * or (at your 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 * Affero General Public License for more details.
15 * You should have received a copy of the GNU Affero General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 * @file peerstore/plugin_peerstore_sqlite.c
21 * @brief sqlite-based peerstore backend
22 * @author Omar Tarabai
23 * @author Christian Grothoff
27 #include "gnunet_peerstore_plugin.h"
28 #include "gnunet_peerstore_service.h"
29 #include "gnunet_sq_lib.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;
101 * Precompiled SQL for deleting expired
102 * records from peerstoredata
104 sqlite3_stmt *expire_peerstoredata;
107 * Precompiled SQL for deleting records
110 sqlite3_stmt *delete_peerstoredata;
116 * Delete records with the given key
118 * @param cls closure (internal context for the plugin)
119 * @param sub_system name of sub system
120 * @param peer Peer identity (can be NULL)
121 * @param key entry key string (can be NULL)
122 * @return number of deleted records, #GNUNE_SYSERR on error
125 peerstore_sqlite_delete_records (void *cls,
126 const char *sub_system,
127 const struct GNUNET_PeerIdentity *peer,
130 struct Plugin *plugin = cls;
131 sqlite3_stmt *stmt = plugin->delete_peerstoredata;
132 struct GNUNET_SQ_QueryParam params[] = {
133 GNUNET_SQ_query_param_string (sub_system),
134 GNUNET_SQ_query_param_auto_from_type (peer),
135 GNUNET_SQ_query_param_string (key),
136 GNUNET_SQ_query_param_end
141 GNUNET_SQ_bind (stmt,
145 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
147 GNUNET_SQ_reset (plugin->dbh,
149 return GNUNET_SYSERR;
155 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
161 ret = sqlite3_changes (plugin->dbh);
163 GNUNET_SQ_reset (plugin->dbh,
170 * Delete expired records (expiry < now)
172 * @param cls closure (internal context for the plugin)
173 * @param now time to use as reference
174 * @param cont continuation called with the number of records expired
175 * @param cont_cls continuation closure
176 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error and cont is not
180 peerstore_sqlite_expire_records (void *cls, struct GNUNET_TIME_Absolute now,
181 GNUNET_PEERSTORE_Continuation cont,
184 struct Plugin *plugin = cls;
185 sqlite3_stmt *stmt = plugin->expire_peerstoredata;
186 struct GNUNET_SQ_QueryParam params[] = {
187 GNUNET_SQ_query_param_absolute_time (&now),
188 GNUNET_SQ_query_param_end
192 GNUNET_SQ_bind (stmt,
196 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
198 GNUNET_SQ_reset (plugin->dbh,
200 return GNUNET_SYSERR;
202 if (SQLITE_DONE != sqlite3_step (stmt))
205 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
207 GNUNET_SQ_reset (plugin->dbh,
209 return GNUNET_SYSERR;
213 sqlite3_changes (plugin->dbh));
214 GNUNET_SQ_reset (plugin->dbh,
221 * Iterate over the records given an optional peer id
224 * @param cls closure (internal context for the plugin)
225 * @param sub_system name of sub system
226 * @param peer Peer identity (can be NULL)
227 * @param key entry key string (can be NULL)
228 * @param iter function to call asynchronously with the results, terminated
230 * @param iter_cls closure for @a iter
231 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error and iter is not
235 peerstore_sqlite_iterate_records (void *cls,
236 const char *sub_system,
237 const struct GNUNET_PeerIdentity *peer,
239 GNUNET_PEERSTORE_Processor iter,
242 struct Plugin *plugin = cls;
246 struct GNUNET_PEERSTORE_Record rec;
248 LOG (GNUNET_ERROR_TYPE_DEBUG,
249 "Executing iterate request on sqlite db.\n");
254 struct GNUNET_SQ_QueryParam params[] = {
255 GNUNET_SQ_query_param_string (sub_system),
256 GNUNET_SQ_query_param_end
259 stmt = plugin->select_peerstoredata;
260 err = GNUNET_SQ_bind (stmt,
265 struct GNUNET_SQ_QueryParam params[] = {
266 GNUNET_SQ_query_param_string (sub_system),
267 GNUNET_SQ_query_param_string (key),
268 GNUNET_SQ_query_param_end
271 stmt = plugin->select_peerstoredata_by_key;
272 err = GNUNET_SQ_bind (stmt,
280 struct GNUNET_SQ_QueryParam params[] = {
281 GNUNET_SQ_query_param_string (sub_system),
282 GNUNET_SQ_query_param_auto_from_type (peer),
283 GNUNET_SQ_query_param_end
286 stmt = plugin->select_peerstoredata_by_pid;
287 err = GNUNET_SQ_bind (stmt,
292 struct GNUNET_SQ_QueryParam params[] = {
293 GNUNET_SQ_query_param_string (sub_system),
294 GNUNET_SQ_query_param_auto_from_type (peer),
295 GNUNET_SQ_query_param_string (key),
296 GNUNET_SQ_query_param_end
299 stmt = plugin->select_peerstoredata_by_all;
300 err = GNUNET_SQ_bind (stmt,
305 if (GNUNET_OK != err)
308 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
309 "sqlite3_bind_XXXX");
310 GNUNET_SQ_reset (plugin->dbh,
312 return GNUNET_SYSERR;
316 while (SQLITE_ROW == (sret = sqlite3_step (stmt)))
318 LOG (GNUNET_ERROR_TYPE_DEBUG,
319 "Returning a matched record.\n");
320 struct GNUNET_SQ_ResultSpec rs[] = {
321 GNUNET_SQ_result_spec_string (&rec.sub_system),
322 GNUNET_SQ_result_spec_auto_from_type (&rec.peer),
323 GNUNET_SQ_result_spec_string (&rec.key),
324 GNUNET_SQ_result_spec_variable_size (&rec.value, &rec.value_size),
325 GNUNET_SQ_result_spec_absolute_time (&rec.expiry),
326 GNUNET_SQ_result_spec_end
330 GNUNET_SQ_extract_result (stmt,
340 GNUNET_SQ_cleanup_result (rs);
342 if (SQLITE_DONE != sret)
345 GNUNET_ERROR_TYPE_ERROR,
349 GNUNET_SQ_reset (plugin->dbh,
354 err ? "sqlite error" : NULL);
360 * Store a record in the peerstore.
361 * Key is the combination of sub system and peer identity.
362 * One key can store multiple values.
364 * @param cls closure (internal context for the plugin)
365 * @param sub_system name of the GNUnet sub system responsible
366 * @param peer peer identity
367 * @param key record key string
368 * @param value value to be stored
369 * @param size size of value to be stored
370 * @param expiry absolute time after which the record is (possibly) deleted
371 * @param options options related to the store operation
372 * @param cont continuation called when record is stored
373 * @param cont_cls continuation closure
374 * @return #GNUNET_OK on success, else #GNUNET_SYSERR and cont is not called
377 peerstore_sqlite_store_record (void *cls,
378 const char *sub_system,
379 const struct GNUNET_PeerIdentity *peer,
383 struct GNUNET_TIME_Absolute expiry,
384 enum GNUNET_PEERSTORE_StoreOption options,
385 GNUNET_PEERSTORE_Continuation cont,
388 struct Plugin *plugin = cls;
389 sqlite3_stmt *stmt = plugin->insert_peerstoredata;
390 struct GNUNET_SQ_QueryParam params[] = {
391 GNUNET_SQ_query_param_string (sub_system),
392 GNUNET_SQ_query_param_auto_from_type (peer),
393 GNUNET_SQ_query_param_string (key),
394 GNUNET_SQ_query_param_fixed_size (value, size),
395 GNUNET_SQ_query_param_absolute_time (&expiry),
396 GNUNET_SQ_query_param_end
399 if (GNUNET_PEERSTORE_STOREOPTION_REPLACE == options)
401 peerstore_sqlite_delete_records (cls,
407 GNUNET_SQ_bind (stmt,
410 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
412 else if (SQLITE_DONE != sqlite3_step (stmt))
415 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
418 GNUNET_SQ_reset (plugin->dbh,
428 * @brief Prepare a SQL statement
430 * @param dbh handle to the database
431 * @param sql SQL statement, UTF-8 encoded
432 * @return 0 on success
435 sql_exec (sqlite3 *dbh,
440 result = sqlite3_exec (dbh,
445 LOG (GNUNET_ERROR_TYPE_DEBUG,
446 "Executed `%s' / %d\n",
449 if (SQLITE_OK != result)
450 LOG (GNUNET_ERROR_TYPE_ERROR,
451 _("Error executing SQL query: %s\n %s\n"),
452 sqlite3_errmsg (dbh),
459 * @brief Prepare a SQL statement
461 * @param dbh handle to the database
462 * @param sql SQL statement, UTF-8 encoded
463 * @param stmt set to the prepared statement
464 * @return 0 on success
467 sql_prepare (sqlite3 *dbh,
469 sqlite3_stmt ** stmt)
474 result = sqlite3_prepare_v2 (dbh,
478 (const char **) &tail);
479 LOG (GNUNET_ERROR_TYPE_DEBUG,
480 "Prepared `%s' / %p: %d\n",
484 if (SQLITE_OK != result)
485 LOG (GNUNET_ERROR_TYPE_ERROR,
486 _("Error preparing SQL query: %s\n %s\n"),
487 sqlite3_errmsg (dbh),
494 * Initialize the database connections and associated
495 * data structures (create tables and indices
496 * as needed as well).
498 * @param plugin the plugin context (state for this module)
499 * @return GNUNET_OK on success
502 database_setup (struct Plugin *plugin)
507 GNUNET_CONFIGURATION_get_value_filename (plugin->cfg,
512 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
515 return GNUNET_SYSERR;
517 if (GNUNET_OK != GNUNET_DISK_file_test (filename))
519 if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (filename))
522 GNUNET_free (filename);
523 return GNUNET_SYSERR;
526 /* filename should be UTF-8-encoded. If it isn't, it's a bug */
527 plugin->fn = filename;
528 /* Open database and precompile statements */
529 if (SQLITE_OK != sqlite3_open (plugin->fn,
532 LOG (GNUNET_ERROR_TYPE_ERROR,
533 _("Unable to initialize SQLite: %s.\n"),
534 sqlite3_errmsg (plugin->dbh));
535 return GNUNET_SYSERR;
537 sql_exec (plugin->dbh,
538 "PRAGMA temp_store=MEMORY");
539 sql_exec (plugin->dbh,
540 "PRAGMA synchronous=OFF");
541 sql_exec (plugin->dbh,
542 "PRAGMA legacy_file_format=OFF");
543 sql_exec (plugin->dbh,
544 "PRAGMA auto_vacuum=INCREMENTAL");
545 sql_exec (plugin->dbh,
546 "PRAGMA encoding=\"UTF-8\"");
547 sql_exec (plugin->dbh,
548 "PRAGMA page_size=4096");
549 sqlite3_busy_timeout (plugin->dbh,
552 sql_exec (plugin->dbh,
553 "CREATE TABLE IF NOT EXISTS peerstoredata (\n"
554 " sub_system TEXT NOT NULL,\n"
555 " peer_id BLOB NOT NULL,\n"
556 " key TEXT NOT NULL,\n"
557 " value BLOB NULL,\n"
558 " expiry INT8 NOT NULL" ");");
561 sqlite3_exec (plugin->dbh,
562 "CREATE INDEX IF NOT EXISTS peerstoredata_key_index ON peerstoredata (sub_system, peer_id, key)",
567 LOG (GNUNET_ERROR_TYPE_ERROR,
568 _("Unable to create indices: %s.\n"),
569 sqlite3_errmsg (plugin->dbh));
570 return GNUNET_SYSERR;
572 /* Prepare statements */
574 sql_prepare (plugin->dbh,
575 "INSERT INTO peerstoredata (sub_system, peer_id, key, value, expiry)"
576 " VALUES (?,?,?,?,?);",
577 &plugin->insert_peerstoredata);
578 sql_prepare (plugin->dbh,
579 "SELECT sub_system,peer_id,key,value,expiry FROM peerstoredata"
580 " WHERE sub_system = ?",
581 &plugin->select_peerstoredata);
582 sql_prepare (plugin->dbh,
583 "SELECT sub_system,peer_id,key,value,expiry FROM peerstoredata"
584 " WHERE sub_system = ?"
586 &plugin->select_peerstoredata_by_pid);
587 sql_prepare (plugin->dbh,
588 "SELECT sub_system,peer_id,key,value,expiry FROM peerstoredata"
589 " WHERE sub_system = ?"
591 &plugin->select_peerstoredata_by_key);
592 sql_prepare (plugin->dbh,
593 "SELECT sub_system,peer_id,key,value,expiry FROM peerstoredata"
594 " WHERE sub_system = ?"
595 " AND peer_id = ?" " AND key = ?",
596 &plugin->select_peerstoredata_by_all);
597 sql_prepare (plugin->dbh,
598 "DELETE FROM peerstoredata"
600 &plugin->expire_peerstoredata);
601 sql_prepare (plugin->dbh,
602 "DELETE FROM peerstoredata"
603 " WHERE sub_system = ?"
604 " AND peer_id = ?" " AND key = ?",
605 &plugin->delete_peerstoredata);
611 * Shutdown database connection and associate data
613 * @param plugin the plugin context (state for this module)
616 database_shutdown (struct Plugin *plugin)
621 while (NULL != (stmt = sqlite3_next_stmt (plugin->dbh,
624 result = sqlite3_finalize (stmt);
625 if (SQLITE_OK != result)
626 LOG (GNUNET_ERROR_TYPE_WARNING,
627 "Failed to close statement %p: %d\n",
631 if (SQLITE_OK != sqlite3_close (plugin->dbh))
633 GNUNET_ERROR_TYPE_ERROR,
635 GNUNET_free_non_null (plugin->fn);
640 * Entry point for the plugin.
642 * @param cls The struct GNUNET_CONFIGURATION_Handle.
643 * @return NULL on error, otherwise the plugin context
646 libgnunet_plugin_peerstore_sqlite_init (void *cls)
648 static struct Plugin plugin;
649 const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
650 struct GNUNET_PEERSTORE_PluginFunctions *api;
652 if (NULL != plugin.cfg)
653 return NULL; /* can only initialize once! */
656 sizeof (struct Plugin));
658 if (GNUNET_OK != database_setup (&plugin))
660 database_shutdown (&plugin);
663 api = GNUNET_new (struct GNUNET_PEERSTORE_PluginFunctions);
665 api->store_record = &peerstore_sqlite_store_record;
666 api->iterate_records = &peerstore_sqlite_iterate_records;
667 api->expire_records = &peerstore_sqlite_expire_records;
668 LOG (GNUNET_ERROR_TYPE_DEBUG,
669 "Sqlite plugin is running\n");
675 * Exit point from the plugin.
677 * @param cls The plugin context (as returned by "init")
678 * @return Always NULL
681 libgnunet_plugin_peerstore_sqlite_done (void *cls)
683 struct GNUNET_PEERSTORE_PluginFunctions *api = cls;
684 struct Plugin *plugin = api->cls;
686 database_shutdown (plugin);
689 LOG (GNUNET_ERROR_TYPE_DEBUG,
690 "Sqlite plugin is finished\n");
694 /* end of plugin_peerstore_sqlite.c */