8d35466de10240adae1409af7a75d242f425afc3
[oweals/gnunet.git] / src / peerstore / plugin_peerstore_sqlite.c
1 /*
2  * This file is part of GNUnet
3  * (C) 2013 Christian Grothoff (and other contributing authors)
4  *
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.
9  *
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.
14  *
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.
19  */
20
21 /**
22  * @file peerstore/plugin_peerstore_sqlite.c
23  * @brief sqlite-based peerstore backend
24  * @author Omar Tarabai
25  */
26
27 #include "platform.h"
28 #include "gnunet_peerstore_plugin.h"
29 #include "gnunet_peerstore_service.h"
30 #include "peerstore.h"
31 #include <sqlite3.h>
32
33 /**
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).
38  *
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.
42  */
43 #define BUSY_TIMEOUT_MS 1000
44
45 /**
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).
49  */
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)
51
52 #define LOG(kind,...) GNUNET_log_from (kind, "peerstore-sqlite", __VA_ARGS__)
53
54 //FIXME: Indexes
55
56 /**
57  * Context for all functions in this plugin.
58  */
59 struct Plugin
60 {
61
62   /**
63    * Configuration handle
64    */
65   const struct GNUNET_CONFIGURATION_Handle *cfg;
66
67   /**
68    * Database filename.
69    */
70   char *fn;
71
72   /**
73    * Native SQLite database handle.
74    */
75   sqlite3 *dbh;
76
77   /**
78    * Precompiled SQL for inserting into peerstoredata
79    */
80   sqlite3_stmt *insert_peerstoredata;
81
82   /**
83    * Precompiled SQL for selecting from peerstoredata
84    */
85   sqlite3_stmt *select_peerstoredata;
86
87   /**
88    * Precompiled SQL for selecting from peerstoredata
89    */
90   sqlite3_stmt *select_peerstoredata_by_pid;
91
92   /**
93    * Precompiled SQL for selecting from peerstoredata
94    */
95   sqlite3_stmt *select_peerstoredata_by_key;
96
97   /**
98    * Precompiled SQL for selecting from peerstoredata
99    */
100   sqlite3_stmt *select_peerstoredata_by_all;
101
102   /**
103    * Precompiled SQL for deleting expired records from peerstoredata
104    */
105   sqlite3_stmt *expire_peerstoredata;
106
107 };
108
109 /**
110  * Delete expired records (expiry < now)
111  *
112  * @param cls closure (internal context for the plugin)
113  * @param now time to use as reference
114  * @return number of records deleted
115  */
116 static int
117 peerstore_sqlite_expire_records(void *cls,
118     struct GNUNET_TIME_Absolute now)
119 {
120   struct Plugin *plugin = cls;
121   sqlite3_stmt *stmt = plugin->expire_peerstoredata;
122
123   if(SQLITE_OK != sqlite3_bind_int64(stmt, 1, (sqlite3_int64)now.abs_value_us))
124   {
125     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, "sqlite3_bind");
126   }
127   else if (SQLITE_DONE != sqlite3_step (stmt))
128   {
129     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
130                 "sqlite3_step");
131   }
132   if (SQLITE_OK != sqlite3_reset (stmt))
133   {
134     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
135                 "sqlite3_reset");
136     return 0;
137   }
138   return sqlite3_changes(plugin->dbh);
139
140 }
141
142 /**
143  * Iterate over the records given an optional peer id
144  * and/or key.
145  *
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
153  */
154 static int
155 peerstore_sqlite_iterate_records (void *cls,
156     const char *sub_system,
157     const struct GNUNET_PeerIdentity *peer,
158     const char *key,
159     GNUNET_PEERSTORE_Processor iter, void *iter_cls)
160 {
161   struct Plugin *plugin = cls;
162   sqlite3_stmt *stmt;
163   int err = 0;
164   int sret;
165   struct GNUNET_PEERSTORE_Record *ret;
166
167   LOG(GNUNET_ERROR_TYPE_DEBUG, "Executing iterate request on sqlite db.\n");
168   if(NULL == peer && NULL == key)
169   {
170     stmt = plugin->select_peerstoredata;
171     err = (SQLITE_OK != sqlite3_bind_text(stmt, 1, sub_system, strlen(sub_system) + 1, SQLITE_STATIC));
172   }
173   else if(NULL == key)
174   {
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));
178   }
179   else if(NULL == peer)
180   {
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));
184   }
185   else
186   {
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));
191   }
192
193   if (err)
194   {
195     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
196     "sqlite3_bind_XXXX");
197     if (SQLITE_OK != sqlite3_reset (stmt))
198       LOG_SQLITE (plugin,
199       GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
200       "sqlite3_reset");
201     return GNUNET_SYSERR;
202   }
203   while (SQLITE_ROW == (sret = sqlite3_step (stmt)))
204   {
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);
214     if (NULL != iter)
215       iter (iter_cls,
216           ret,
217           NULL);
218   }
219   if (SQLITE_DONE != sret)
220   {
221     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite_step");
222     err = 1;
223   }
224   if (SQLITE_OK != sqlite3_reset (stmt))
225   {
226     LOG_SQLITE (plugin,
227     GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
228     "sqlite3_reset");
229     err = 1;
230   }
231   if(err)
232     return GNUNET_SYSERR;
233   return GNUNET_OK;
234 }
235
236 /**
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.
240  *
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
247  */
248 static int
249 peerstore_sqlite_store_record(void *cls,
250     const char *sub_system,
251     const struct GNUNET_PeerIdentity *peer,
252     const char *key,
253     const void *value,
254     size_t size,
255     struct GNUNET_TIME_Absolute expiry)
256 {
257   struct Plugin *plugin = cls;
258   sqlite3_stmt *stmt = plugin->insert_peerstoredata;
259
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,
266                     "sqlite3_bind");
267   else if (SQLITE_DONE != sqlite3_step (stmt))
268   {
269     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
270                 "sqlite3_step");
271   }
272   if (SQLITE_OK != sqlite3_reset (stmt))
273   {
274     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
275                 "sqlite3_reset");
276     return GNUNET_SYSERR;
277   }
278
279   return GNUNET_OK;
280 }
281
282
283 /**
284  * @brief Prepare a SQL statement
285  *
286  * @param dbh handle to the database
287  * @param sql SQL statement, UTF-8 encoded
288  * @return 0 on success
289  */
290 static int
291 sql_exec (sqlite3 *dbh, const char *sql)
292 {
293   int result;
294
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);
302   return result;
303 }
304
305 /**
306  * @brief Prepare a SQL statement
307  *
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
312  */
313 static int
314 sql_prepare (sqlite3 *dbh, const char *sql, sqlite3_stmt **stmt)
315 {
316   char *tail;
317   int result;
318
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);
327   return result;
328 }
329
330 /**
331  * Initialize the database connections and associated
332  * data structures (create tables and indices
333  * as needed as well).
334  *
335  * @param plugin the plugin context (state for this module)
336  * @return GNUNET_OK on success
337  */
338 static int
339 database_setup (struct Plugin *plugin)
340 {
341   char *filename;
342
343   if (GNUNET_OK !=
344       GNUNET_CONFIGURATION_get_value_filename (plugin->cfg, "peerstore-sqlite",
345                                                "FILENAME", &filename))
346   {
347     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
348              "peerstore-sqlite", "FILENAME");
349     return GNUNET_SYSERR;
350   }
351   if (GNUNET_OK != GNUNET_DISK_file_test (filename))
352   {
353     if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (filename))
354     {
355       GNUNET_break (0);
356       GNUNET_free (filename);
357       return GNUNET_SYSERR;
358     }
359   }
360   /* filename should be UTF-8-encoded. If it isn't, it's a bug */
361   plugin->fn = filename;
362
363   /* Open database and precompile statements */
364   if (SQLITE_OK != sqlite3_open (plugin->fn, &plugin->dbh))
365   {
366     LOG (GNUNET_ERROR_TYPE_ERROR,
367    _("Unable to initialize SQLite: %s.\n"),
368    sqlite3_errmsg (plugin->dbh));
369     return GNUNET_SYSERR;
370   }
371
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");
379
380   sqlite3_busy_timeout (plugin->dbh, BUSY_TIMEOUT_MS);
381
382   /* Create tables */
383
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"
391       ");");
392
393   /* Prepare statements */
394
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 = ?"
405       " AND peer_id = ?",
406       &plugin->select_peerstoredata_by_pid);
407   sql_prepare(plugin->dbh,
408       "SELECT * FROM peerstoredata"
409       " WHERE sub_system = ?"
410       " AND key = ?",
411       &plugin->select_peerstoredata_by_key);
412   sql_prepare(plugin->dbh,
413       "SELECT * FROM peerstoredata"
414       " WHERE sub_system = ?"
415       " AND peer_id = ?"
416       " AND key = ?",
417       &plugin->select_peerstoredata_by_all);
418   sql_prepare(plugin->dbh,
419       "DELETE FROM peerstoredata"
420       " WHERE expiry < ?",
421       &plugin->expire_peerstoredata);
422
423   return GNUNET_OK;
424 }
425
426 /**
427  * Shutdown database connection and associate data
428  * structures.
429  * @param plugin the plugin context (state for this module)
430  */
431 static void
432 database_shutdown (struct Plugin *plugin)
433 {
434   int result;
435   sqlite3_stmt *stmt;
436   while (NULL != (stmt = sqlite3_next_stmt (plugin->dbh, NULL)))
437   {
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);
442   }
443   if (SQLITE_OK != sqlite3_close (plugin->dbh))
444     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close");
445
446   GNUNET_free_non_null (plugin->fn);
447 }
448
449 /**
450  * Entry point for the plugin.
451  *
452  * @param cls The struct GNUNET_CONFIGURATION_Handle.
453  * @return NULL on error, otherwise the plugin context
454  */
455 void *
456 libgnunet_plugin_peerstore_sqlite_init (void *cls)
457 {
458   static struct Plugin plugin;
459   const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
460   struct GNUNET_PEERSTORE_PluginFunctions *api;
461
462   if (NULL != plugin.cfg)
463     return NULL;                /* can only initialize once! */
464   memset (&plugin, 0, sizeof (struct Plugin));
465   plugin.cfg = cfg;
466   if (GNUNET_OK != database_setup (&plugin))
467   {
468     database_shutdown (&plugin);
469     return NULL;
470   }
471   api = GNUNET_new (struct GNUNET_PEERSTORE_PluginFunctions);
472   api->cls = &plugin;
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");
477   return api;
478 }
479
480 /**
481  * Exit point from the plugin.
482  *
483  * @param cls The plugin context (as returned by "init")
484  * @return Always NULL
485  */
486 void *
487 libgnunet_plugin_peerstore_sqlite_done (void *cls)
488 {
489   struct GNUNET_PEERSTORE_PluginFunctions *api = cls;
490   struct Plugin *plugin = api->cls;
491
492   database_shutdown (plugin);
493   plugin->cfg = NULL;
494   GNUNET_free (api);
495   LOG (GNUNET_ERROR_TYPE_DEBUG, "Sqlite plugin is finished\n");
496   return NULL;
497
498 }
499
500 /* end of plugin_peerstore_sqlite.c */