8705ce1880d2b6343157673256b13e59ef02ba67
[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     GNUNET_free(ret->expiry);
219     GNUNET_free(ret);
220   }
221   if (SQLITE_DONE != sret)
222   {
223     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite_step");
224     err = 1;
225   }
226   if (SQLITE_OK != sqlite3_reset (stmt))
227   {
228     LOG_SQLITE (plugin,
229     GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
230     "sqlite3_reset");
231     err = 1;
232   }
233   if(err)
234     return GNUNET_SYSERR;
235   return GNUNET_OK;
236 }
237
238 /**
239  * Store a record in the peerstore.
240  * Key is the combination of sub system and peer identity.
241  * One key can store multiple values.
242  *
243  * @param cls closure (internal context for the plugin)
244  * @param peer peer identity
245  * @param sub_system name of the GNUnet sub system responsible
246  * @param value value to be stored
247  * @param size size of value to be stored
248  * @return #GNUNET_OK on success, else #GNUNET_SYSERR
249  */
250 static int
251 peerstore_sqlite_store_record(void *cls,
252     const char *sub_system,
253     const struct GNUNET_PeerIdentity *peer,
254     const char *key,
255     const void *value,
256     size_t size,
257     struct GNUNET_TIME_Absolute expiry)
258 {
259   struct Plugin *plugin = cls;
260   sqlite3_stmt *stmt = plugin->insert_peerstoredata;
261
262   if(SQLITE_OK != sqlite3_bind_text(stmt, 1, sub_system, strlen(sub_system) + 1, SQLITE_STATIC)
263       || SQLITE_OK != sqlite3_bind_blob(stmt, 2, peer, sizeof(struct GNUNET_PeerIdentity), SQLITE_STATIC)
264       || SQLITE_OK != sqlite3_bind_text(stmt, 3, key, strlen(key) + 1, SQLITE_STATIC)
265       || SQLITE_OK != sqlite3_bind_blob(stmt, 4, value, size, SQLITE_STATIC)
266       || SQLITE_OK != sqlite3_bind_int64(stmt, 5, (sqlite3_int64)expiry.abs_value_us))
267     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
268                     "sqlite3_bind");
269   else if (SQLITE_DONE != sqlite3_step (stmt))
270   {
271     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
272                 "sqlite3_step");
273   }
274   if (SQLITE_OK != sqlite3_reset (stmt))
275   {
276     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
277                 "sqlite3_reset");
278     return GNUNET_SYSERR;
279   }
280
281   return GNUNET_OK;
282 }
283
284
285 /**
286  * @brief Prepare a SQL statement
287  *
288  * @param dbh handle to the database
289  * @param sql SQL statement, UTF-8 encoded
290  * @return 0 on success
291  */
292 static int
293 sql_exec (sqlite3 *dbh, const char *sql)
294 {
295   int result;
296
297   result = sqlite3_exec (dbh, sql, NULL, NULL, NULL);
298   LOG (GNUNET_ERROR_TYPE_DEBUG,
299        "Executed `%s' / %d\n", sql, result);
300   if (result != SQLITE_OK)
301     LOG (GNUNET_ERROR_TYPE_ERROR,
302    _("Error executing SQL query: %s\n  %s\n"),
303    sqlite3_errmsg (dbh), sql);
304   return result;
305 }
306
307 /**
308  * @brief Prepare a SQL statement
309  *
310  * @param dbh handle to the database
311  * @param sql SQL statement, UTF-8 encoded
312  * @param stmt set to the prepared statement
313  * @return 0 on success
314  */
315 static int
316 sql_prepare (sqlite3 *dbh, const char *sql, sqlite3_stmt **stmt)
317 {
318   char *tail;
319   int result;
320
321   result = sqlite3_prepare_v2 (dbh, sql, strlen (sql), stmt,
322                                (const char **) &tail);
323   LOG (GNUNET_ERROR_TYPE_DEBUG,
324        "Prepared `%s' / %p: %d\n", sql, *stmt, result);
325   if (result != SQLITE_OK)
326     LOG (GNUNET_ERROR_TYPE_ERROR,
327    _("Error preparing SQL query: %s\n  %s\n"),
328    sqlite3_errmsg (dbh), sql);
329   return result;
330 }
331
332 /**
333  * Initialize the database connections and associated
334  * data structures (create tables and indices
335  * as needed as well).
336  *
337  * @param plugin the plugin context (state for this module)
338  * @return GNUNET_OK on success
339  */
340 static int
341 database_setup (struct Plugin *plugin)
342 {
343   char *filename;
344
345   if (GNUNET_OK !=
346       GNUNET_CONFIGURATION_get_value_filename (plugin->cfg, "peerstore-sqlite",
347                                                "FILENAME", &filename))
348   {
349     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
350              "peerstore-sqlite", "FILENAME");
351     return GNUNET_SYSERR;
352   }
353   if (GNUNET_OK != GNUNET_DISK_file_test (filename))
354   {
355     if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (filename))
356     {
357       GNUNET_break (0);
358       GNUNET_free (filename);
359       return GNUNET_SYSERR;
360     }
361   }
362   /* filename should be UTF-8-encoded. If it isn't, it's a bug */
363   plugin->fn = filename;
364
365   /* Open database and precompile statements */
366   if (SQLITE_OK != sqlite3_open (plugin->fn, &plugin->dbh))
367   {
368     LOG (GNUNET_ERROR_TYPE_ERROR,
369    _("Unable to initialize SQLite: %s.\n"),
370    sqlite3_errmsg (plugin->dbh));
371     return GNUNET_SYSERR;
372   }
373
374   sql_exec (plugin->dbh, "PRAGMA temp_store=MEMORY");
375   sql_exec (plugin->dbh, "PRAGMA synchronous=NORMAL");
376   sql_exec (plugin->dbh, "PRAGMA legacy_file_format=OFF");
377   sql_exec (plugin->dbh, "PRAGMA auto_vacuum=INCREMENTAL");
378   sql_exec (plugin->dbh, "PRAGMA encoding=\"UTF-8\"");
379   sql_exec (plugin->dbh, "PRAGMA count_changes=OFF");
380   sql_exec (plugin->dbh, "PRAGMA page_size=4096");
381
382   sqlite3_busy_timeout (plugin->dbh, BUSY_TIMEOUT_MS);
383
384   /* Create tables */
385
386   sql_exec (plugin->dbh,
387       "CREATE TABLE IF NOT EXISTS peerstoredata (\n"
388       "  sub_system TEXT NOT NULL,\n"
389       "  peer_id BLOB NOT NULL,\n"
390       "  key TEXT NOT NULL,\n"
391       "  value BLOB NULL,\n"
392       "  expiry INTEGER NOT NULL"
393       ");");
394
395   /* Prepare statements */
396
397   sql_prepare (plugin->dbh,
398       "INSERT INTO peerstoredata (sub_system, peer_id, key, value, expiry) VALUES (?,?,?,?,?);",
399       &plugin->insert_peerstoredata);
400   sql_prepare(plugin->dbh,
401       "SELECT * FROM peerstoredata"
402       " WHERE sub_system = ?",
403       &plugin->select_peerstoredata);
404   sql_prepare(plugin->dbh,
405       "SELECT * FROM peerstoredata"
406       " WHERE sub_system = ?"
407       " AND peer_id = ?",
408       &plugin->select_peerstoredata_by_pid);
409   sql_prepare(plugin->dbh,
410       "SELECT * FROM peerstoredata"
411       " WHERE sub_system = ?"
412       " AND key = ?",
413       &plugin->select_peerstoredata_by_key);
414   sql_prepare(plugin->dbh,
415       "SELECT * FROM peerstoredata"
416       " WHERE sub_system = ?"
417       " AND peer_id = ?"
418       " AND key = ?",
419       &plugin->select_peerstoredata_by_all);
420   sql_prepare(plugin->dbh,
421       "DELETE FROM peerstoredata"
422       " WHERE expiry < ?",
423       &plugin->expire_peerstoredata);
424
425   return GNUNET_OK;
426 }
427
428 /**
429  * Shutdown database connection and associate data
430  * structures.
431  * @param plugin the plugin context (state for this module)
432  */
433 static void
434 database_shutdown (struct Plugin *plugin)
435 {
436   int result;
437   sqlite3_stmt *stmt;
438   while (NULL != (stmt = sqlite3_next_stmt (plugin->dbh, NULL)))
439   {
440     result = sqlite3_finalize (stmt);
441     if (SQLITE_OK != result)
442       LOG (GNUNET_ERROR_TYPE_WARNING,
443            "Failed to close statement %p: %d\n", stmt, result);
444   }
445   if (SQLITE_OK != sqlite3_close (plugin->dbh))
446     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close");
447
448   GNUNET_free_non_null (plugin->fn);
449 }
450
451 /**
452  * Entry point for the plugin.
453  *
454  * @param cls The struct GNUNET_CONFIGURATION_Handle.
455  * @return NULL on error, otherwise the plugin context
456  */
457 void *
458 libgnunet_plugin_peerstore_sqlite_init (void *cls)
459 {
460   static struct Plugin plugin;
461   const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
462   struct GNUNET_PEERSTORE_PluginFunctions *api;
463
464   if (NULL != plugin.cfg)
465     return NULL;                /* can only initialize once! */
466   memset (&plugin, 0, sizeof (struct Plugin));
467   plugin.cfg = cfg;
468   if (GNUNET_OK != database_setup (&plugin))
469   {
470     database_shutdown (&plugin);
471     return NULL;
472   }
473   api = GNUNET_new (struct GNUNET_PEERSTORE_PluginFunctions);
474   api->cls = &plugin;
475   api->store_record = &peerstore_sqlite_store_record;
476   api->iterate_records = &peerstore_sqlite_iterate_records;
477   api->expire_records = &peerstore_sqlite_expire_records;
478   LOG(GNUNET_ERROR_TYPE_DEBUG, "Sqlite plugin is running\n");
479   return api;
480 }
481
482 /**
483  * Exit point from the plugin.
484  *
485  * @param cls The plugin context (as returned by "init")
486  * @return Always NULL
487  */
488 void *
489 libgnunet_plugin_peerstore_sqlite_done (void *cls)
490 {
491   struct GNUNET_PEERSTORE_PluginFunctions *api = cls;
492   struct Plugin *plugin = api->cls;
493
494   database_shutdown (plugin);
495   plugin->cfg = NULL;
496   GNUNET_free (api);
497   LOG (GNUNET_ERROR_TYPE_DEBUG, "Sqlite plugin is finished\n");
498   return NULL;
499
500 }
501
502 /* end of plugin_peerstore_sqlite.c */