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 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.
17 * @file peerstore/plugin_peerstore_sqlite.c
18 * @brief sqlite-based peerstore backend
19 * @author Omar Tarabai
20 * @author Christian Grothoff
24 #include "gnunet_peerstore_plugin.h"
25 #include "gnunet_peerstore_service.h"
26 #include "gnunet_sq_lib.h"
27 #include "peerstore.h"
31 * After how many ms "busy" should a DB operation fail for good? A
32 * low value makes sure that we are more responsive to requests
33 * (especially PUTs). A high value guarantees a higher success rate
34 * (SELECTs in iterate can take several seconds despite LIMIT=1).
36 * The default value of 1s should ensure that users do not experience
37 * huge latencies while at the same time allowing operations to
38 * succeed with reasonable probability.
40 #define BUSY_TIMEOUT_MS 1000
43 * Log an error message at log-level 'level' that indicates
44 * a failure of the command 'cmd' on file 'filename'
45 * with the message given by strerror(errno).
47 #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)
49 #define LOG(kind,...) GNUNET_log_from (kind, "peerstore-sqlite", __VA_ARGS__)
52 * Context for all functions in this plugin.
58 * Configuration handle
60 const struct GNUNET_CONFIGURATION_Handle *cfg;
68 * Native SQLite database handle.
73 * Precompiled SQL for inserting into peerstoredata
75 sqlite3_stmt *insert_peerstoredata;
78 * Precompiled SQL for selecting from peerstoredata
80 sqlite3_stmt *select_peerstoredata;
83 * Precompiled SQL for selecting from peerstoredata
85 sqlite3_stmt *select_peerstoredata_by_pid;
88 * Precompiled SQL for selecting from peerstoredata
90 sqlite3_stmt *select_peerstoredata_by_key;
93 * Precompiled SQL for selecting from peerstoredata
95 sqlite3_stmt *select_peerstoredata_by_all;
98 * Precompiled SQL for deleting expired
99 * records from peerstoredata
101 sqlite3_stmt *expire_peerstoredata;
104 * Precompiled SQL for deleting records
107 sqlite3_stmt *delete_peerstoredata;
113 * Delete records with the given key
115 * @param cls closure (internal context for the plugin)
116 * @param sub_system name of sub system
117 * @param peer Peer identity (can be NULL)
118 * @param key entry key string (can be NULL)
119 * @return number of deleted records, #GNUNE_SYSERR on error
122 peerstore_sqlite_delete_records (void *cls,
123 const char *sub_system,
124 const struct GNUNET_PeerIdentity *peer,
127 struct Plugin *plugin = cls;
128 sqlite3_stmt *stmt = plugin->delete_peerstoredata;
129 struct GNUNET_SQ_QueryParam params[] = {
130 GNUNET_SQ_query_param_string (sub_system),
131 GNUNET_SQ_query_param_auto_from_type (peer),
132 GNUNET_SQ_query_param_string (key),
133 GNUNET_SQ_query_param_end
138 GNUNET_SQ_bind (stmt,
142 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
144 GNUNET_SQ_reset (plugin->dbh,
146 return GNUNET_SYSERR;
152 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
158 ret = sqlite3_changes (plugin->dbh);
160 GNUNET_SQ_reset (plugin->dbh,
167 * Delete expired records (expiry < now)
169 * @param cls closure (internal context for the plugin)
170 * @param now time to use as reference
171 * @param cont continuation called with the number of records expired
172 * @param cont_cls continuation closure
173 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error and cont is not
177 peerstore_sqlite_expire_records (void *cls, struct GNUNET_TIME_Absolute now,
178 GNUNET_PEERSTORE_Continuation cont,
181 struct Plugin *plugin = cls;
182 sqlite3_stmt *stmt = plugin->expire_peerstoredata;
183 struct GNUNET_SQ_QueryParam params[] = {
184 GNUNET_SQ_query_param_absolute_time (&now),
185 GNUNET_SQ_query_param_end
189 GNUNET_SQ_bind (stmt,
193 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
195 GNUNET_SQ_reset (plugin->dbh,
197 return GNUNET_SYSERR;
199 if (SQLITE_DONE != sqlite3_step (stmt))
202 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
204 GNUNET_SQ_reset (plugin->dbh,
206 return GNUNET_SYSERR;
210 sqlite3_changes (plugin->dbh));
211 GNUNET_SQ_reset (plugin->dbh,
218 * Iterate over the records given an optional peer id
221 * @param cls closure (internal context for the plugin)
222 * @param sub_system name of sub system
223 * @param peer Peer identity (can be NULL)
224 * @param key entry key string (can be NULL)
225 * @param iter function to call asynchronously with the results, terminated
227 * @param iter_cls closure for @a iter
228 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error and iter is not
232 peerstore_sqlite_iterate_records (void *cls,
233 const char *sub_system,
234 const struct GNUNET_PeerIdentity *peer,
236 GNUNET_PEERSTORE_Processor iter,
239 struct Plugin *plugin = cls;
243 struct GNUNET_PEERSTORE_Record rec;
245 LOG (GNUNET_ERROR_TYPE_DEBUG,
246 "Executing iterate request on sqlite db.\n");
251 struct GNUNET_SQ_QueryParam params[] = {
252 GNUNET_SQ_query_param_string (sub_system),
253 GNUNET_SQ_query_param_end
256 stmt = plugin->select_peerstoredata;
257 err = GNUNET_SQ_bind (stmt,
262 struct GNUNET_SQ_QueryParam params[] = {
263 GNUNET_SQ_query_param_string (sub_system),
264 GNUNET_SQ_query_param_string (key),
265 GNUNET_SQ_query_param_end
268 stmt = plugin->select_peerstoredata_by_key;
269 err = GNUNET_SQ_bind (stmt,
277 struct GNUNET_SQ_QueryParam params[] = {
278 GNUNET_SQ_query_param_string (sub_system),
279 GNUNET_SQ_query_param_auto_from_type (peer),
280 GNUNET_SQ_query_param_end
283 stmt = plugin->select_peerstoredata_by_pid;
284 err = GNUNET_SQ_bind (stmt,
289 struct GNUNET_SQ_QueryParam params[] = {
290 GNUNET_SQ_query_param_string (sub_system),
291 GNUNET_SQ_query_param_auto_from_type (peer),
292 GNUNET_SQ_query_param_string (key),
293 GNUNET_SQ_query_param_end
296 stmt = plugin->select_peerstoredata_by_all;
297 err = GNUNET_SQ_bind (stmt,
302 if (GNUNET_OK != err)
305 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
306 "sqlite3_bind_XXXX");
307 GNUNET_SQ_reset (plugin->dbh,
309 return GNUNET_SYSERR;
313 while (SQLITE_ROW == (sret = sqlite3_step (stmt)))
315 LOG (GNUNET_ERROR_TYPE_DEBUG,
316 "Returning a matched record.\n");
317 struct GNUNET_SQ_ResultSpec rs[] = {
318 GNUNET_SQ_result_spec_string (&rec.sub_system),
319 GNUNET_SQ_result_spec_auto_from_type (&rec.peer),
320 GNUNET_SQ_result_spec_string (&rec.key),
321 GNUNET_SQ_result_spec_variable_size (&rec.value, &rec.value_size),
322 GNUNET_SQ_result_spec_absolute_time (&rec.expiry),
323 GNUNET_SQ_result_spec_end
327 GNUNET_SQ_extract_result (stmt,
337 GNUNET_SQ_cleanup_result (rs);
339 if (SQLITE_DONE != sret)
342 GNUNET_ERROR_TYPE_ERROR,
346 GNUNET_SQ_reset (plugin->dbh,
351 err ? "sqlite error" : NULL);
357 * Store a record in the peerstore.
358 * Key is the combination of sub system and peer identity.
359 * One key can store multiple values.
361 * @param cls closure (internal context for the plugin)
362 * @param sub_system name of the GNUnet sub system responsible
363 * @param peer peer identity
364 * @param key record key string
365 * @param value value to be stored
366 * @param size size of value to be stored
367 * @param expiry absolute time after which the record is (possibly) deleted
368 * @param options options related to the store operation
369 * @param cont continuation called when record is stored
370 * @param cont_cls continuation closure
371 * @return #GNUNET_OK on success, else #GNUNET_SYSERR and cont is not called
374 peerstore_sqlite_store_record (void *cls,
375 const char *sub_system,
376 const struct GNUNET_PeerIdentity *peer,
380 struct GNUNET_TIME_Absolute expiry,
381 enum GNUNET_PEERSTORE_StoreOption options,
382 GNUNET_PEERSTORE_Continuation cont,
385 struct Plugin *plugin = cls;
386 sqlite3_stmt *stmt = plugin->insert_peerstoredata;
387 struct GNUNET_SQ_QueryParam params[] = {
388 GNUNET_SQ_query_param_string (sub_system),
389 GNUNET_SQ_query_param_auto_from_type (peer),
390 GNUNET_SQ_query_param_string (key),
391 GNUNET_SQ_query_param_fixed_size (value, size),
392 GNUNET_SQ_query_param_absolute_time (&expiry),
393 GNUNET_SQ_query_param_end
396 if (GNUNET_PEERSTORE_STOREOPTION_REPLACE == options)
398 peerstore_sqlite_delete_records (cls,
404 GNUNET_SQ_bind (stmt,
407 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
409 else if (SQLITE_DONE != sqlite3_step (stmt))
412 GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
415 GNUNET_SQ_reset (plugin->dbh,
425 * @brief Prepare a SQL statement
427 * @param dbh handle to the database
428 * @param sql SQL statement, UTF-8 encoded
429 * @return 0 on success
432 sql_exec (sqlite3 *dbh,
437 result = sqlite3_exec (dbh,
442 LOG (GNUNET_ERROR_TYPE_DEBUG,
443 "Executed `%s' / %d\n",
446 if (SQLITE_OK != result)
447 LOG (GNUNET_ERROR_TYPE_ERROR,
448 _("Error executing SQL query: %s\n %s\n"),
449 sqlite3_errmsg (dbh),
456 * @brief Prepare a SQL statement
458 * @param dbh handle to the database
459 * @param sql SQL statement, UTF-8 encoded
460 * @param stmt set to the prepared statement
461 * @return 0 on success
464 sql_prepare (sqlite3 *dbh,
466 sqlite3_stmt ** stmt)
471 result = sqlite3_prepare_v2 (dbh,
475 (const char **) &tail);
476 LOG (GNUNET_ERROR_TYPE_DEBUG,
477 "Prepared `%s' / %p: %d\n",
481 if (SQLITE_OK != result)
482 LOG (GNUNET_ERROR_TYPE_ERROR,
483 _("Error preparing SQL query: %s\n %s\n"),
484 sqlite3_errmsg (dbh),
491 * Initialize the database connections and associated
492 * data structures (create tables and indices
493 * as needed as well).
495 * @param plugin the plugin context (state for this module)
496 * @return GNUNET_OK on success
499 database_setup (struct Plugin *plugin)
504 GNUNET_CONFIGURATION_get_value_filename (plugin->cfg,
509 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
512 return GNUNET_SYSERR;
514 if (GNUNET_OK != GNUNET_DISK_file_test (filename))
516 if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (filename))
519 GNUNET_free (filename);
520 return GNUNET_SYSERR;
523 /* filename should be UTF-8-encoded. If it isn't, it's a bug */
524 plugin->fn = filename;
525 /* Open database and precompile statements */
526 if (SQLITE_OK != sqlite3_open (plugin->fn,
529 LOG (GNUNET_ERROR_TYPE_ERROR,
530 _("Unable to initialize SQLite: %s.\n"),
531 sqlite3_errmsg (plugin->dbh));
532 return GNUNET_SYSERR;
534 sql_exec (plugin->dbh,
535 "PRAGMA temp_store=MEMORY");
536 sql_exec (plugin->dbh,
537 "PRAGMA synchronous=OFF");
538 sql_exec (plugin->dbh,
539 "PRAGMA legacy_file_format=OFF");
540 sql_exec (plugin->dbh,
541 "PRAGMA auto_vacuum=INCREMENTAL");
542 sql_exec (plugin->dbh,
543 "PRAGMA encoding=\"UTF-8\"");
544 sql_exec (plugin->dbh,
545 "PRAGMA page_size=4096");
546 sqlite3_busy_timeout (plugin->dbh,
549 sql_exec (plugin->dbh,
550 "CREATE TABLE IF NOT EXISTS peerstoredata (\n"
551 " sub_system TEXT NOT NULL,\n"
552 " peer_id BLOB NOT NULL,\n"
553 " key TEXT NOT NULL,\n"
554 " value BLOB NULL,\n"
555 " expiry INT8 NOT NULL" ");");
558 sqlite3_exec (plugin->dbh,
559 "CREATE INDEX IF NOT EXISTS peerstoredata_key_index ON peerstoredata (sub_system, peer_id, key)",
564 LOG (GNUNET_ERROR_TYPE_ERROR,
565 _("Unable to create indices: %s.\n"),
566 sqlite3_errmsg (plugin->dbh));
567 return GNUNET_SYSERR;
569 /* Prepare statements */
571 sql_prepare (plugin->dbh,
572 "INSERT INTO peerstoredata (sub_system, peer_id, key, value, expiry)"
573 " VALUES (?,?,?,?,?);",
574 &plugin->insert_peerstoredata);
575 sql_prepare (plugin->dbh,
576 "SELECT sub_system,peer_id,key,value,expiry FROM peerstoredata"
577 " WHERE sub_system = ?",
578 &plugin->select_peerstoredata);
579 sql_prepare (plugin->dbh,
580 "SELECT sub_system,peer_id,key,value,expiry FROM peerstoredata"
581 " WHERE sub_system = ?"
583 &plugin->select_peerstoredata_by_pid);
584 sql_prepare (plugin->dbh,
585 "SELECT sub_system,peer_id,key,value,expiry FROM peerstoredata"
586 " WHERE sub_system = ?"
588 &plugin->select_peerstoredata_by_key);
589 sql_prepare (plugin->dbh,
590 "SELECT sub_system,peer_id,key,value,expiry FROM peerstoredata"
591 " WHERE sub_system = ?"
592 " AND peer_id = ?" " AND key = ?",
593 &plugin->select_peerstoredata_by_all);
594 sql_prepare (plugin->dbh,
595 "DELETE FROM peerstoredata"
597 &plugin->expire_peerstoredata);
598 sql_prepare (plugin->dbh,
599 "DELETE FROM peerstoredata"
600 " WHERE sub_system = ?"
601 " AND peer_id = ?" " AND key = ?",
602 &plugin->delete_peerstoredata);
608 * Shutdown database connection and associate data
610 * @param plugin the plugin context (state for this module)
613 database_shutdown (struct Plugin *plugin)
618 while (NULL != (stmt = sqlite3_next_stmt (plugin->dbh,
621 result = sqlite3_finalize (stmt);
622 if (SQLITE_OK != result)
623 LOG (GNUNET_ERROR_TYPE_WARNING,
624 "Failed to close statement %p: %d\n",
628 if (SQLITE_OK != sqlite3_close (plugin->dbh))
630 GNUNET_ERROR_TYPE_ERROR,
632 GNUNET_free_non_null (plugin->fn);
637 * Entry point for the plugin.
639 * @param cls The struct GNUNET_CONFIGURATION_Handle.
640 * @return NULL on error, otherwise the plugin context
643 libgnunet_plugin_peerstore_sqlite_init (void *cls)
645 static struct Plugin plugin;
646 const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
647 struct GNUNET_PEERSTORE_PluginFunctions *api;
649 if (NULL != plugin.cfg)
650 return NULL; /* can only initialize once! */
653 sizeof (struct Plugin));
655 if (GNUNET_OK != database_setup (&plugin))
657 database_shutdown (&plugin);
660 api = GNUNET_new (struct GNUNET_PEERSTORE_PluginFunctions);
662 api->store_record = &peerstore_sqlite_store_record;
663 api->iterate_records = &peerstore_sqlite_iterate_records;
664 api->expire_records = &peerstore_sqlite_expire_records;
665 LOG (GNUNET_ERROR_TYPE_DEBUG,
666 "Sqlite plugin is running\n");
672 * Exit point from the plugin.
674 * @param cls The plugin context (as returned by "init")
675 * @return Always NULL
678 libgnunet_plugin_peerstore_sqlite_done (void *cls)
680 struct GNUNET_PEERSTORE_PluginFunctions *api = cls;
681 struct Plugin *plugin = api->cls;
683 database_shutdown (plugin);
686 LOG (GNUNET_ERROR_TYPE_DEBUG,
687 "Sqlite plugin is finished\n");
691 /* end of plugin_peerstore_sqlite.c */