Exponential backoff for find finger trail task
[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 /**
55  * Context for all functions in this plugin.
56  */
57 struct Plugin
58 {
59
60   /**
61    * Configuration handle
62    */
63   const struct GNUNET_CONFIGURATION_Handle *cfg;
64
65   /**
66    * Database filename.
67    */
68   char *fn;
69
70   /**
71    * Native SQLite database handle.
72    */
73   sqlite3 *dbh;
74
75   /**
76    * Precompiled SQL for inserting into peerstoredata
77    */
78   sqlite3_stmt *insert_peerstoredata;
79
80   /**
81    * Precompiled SQL for selecting from peerstoredata
82    */
83   sqlite3_stmt *select_peerstoredata;
84
85   /**
86    * Precompiled SQL for selecting from peerstoredata
87    */
88   sqlite3_stmt *select_peerstoredata_by_pid;
89
90   /**
91    * Precompiled SQL for selecting from peerstoredata
92    */
93   sqlite3_stmt *select_peerstoredata_by_key;
94
95   /**
96    * Precompiled SQL for selecting from peerstoredata
97    */
98   sqlite3_stmt *select_peerstoredata_by_all;
99
100   /**
101    * Precompiled SQL for deleting expired
102    * records from peerstoredata
103    */
104   sqlite3_stmt *expire_peerstoredata;
105
106   /**
107    * Precompiled SQL for deleting records
108    * with given key
109    */
110   sqlite3_stmt *delete_peerstoredata;
111
112 };
113
114 /**
115  * Delete records with the given key
116  *
117  * @param cls closure (internal context for the plugin)
118  * @param sub_system name of sub system
119  * @param peer Peer identity (can be NULL)
120  * @param key entry key string (can be NULL)
121  * @return number of deleted records
122  */
123 static int
124 peerstore_sqlite_delete_records (void *cls, const char *sub_system,
125                                  const struct GNUNET_PeerIdentity *peer,
126                                  const char *key)
127 {
128   struct Plugin *plugin = cls;
129   sqlite3_stmt *stmt = plugin->delete_peerstoredata;
130
131   if ((SQLITE_OK !=
132        sqlite3_bind_text (stmt, 1, sub_system, strlen (sub_system) + 1,
133                           SQLITE_STATIC)) ||
134       (SQLITE_OK !=
135        sqlite3_bind_blob (stmt, 2, peer, sizeof (struct GNUNET_PeerIdentity),
136                           SQLITE_STATIC)) ||
137       (SQLITE_OK !=
138        sqlite3_bind_text (stmt, 3, key, strlen (key) + 1, SQLITE_STATIC)))
139   {
140     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
141                 "sqlite3_bind");
142   }
143   else if (SQLITE_DONE != sqlite3_step (stmt))
144   {
145     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
146                 "sqlite3_step");
147   }
148   if (SQLITE_OK != sqlite3_reset (stmt))
149   {
150     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
151                 "sqlite3_reset");
152     return 0;
153   }
154   return sqlite3_changes (plugin->dbh);
155 }
156
157
158 /**
159  * Delete expired records (expiry < now)
160  *
161  * @param cls closure (internal context for the plugin)
162  * @param now time to use as reference
163  * @return number of records deleted
164  */
165 static int
166 peerstore_sqlite_expire_records (void *cls, struct GNUNET_TIME_Absolute now)
167 {
168   struct Plugin *plugin = cls;
169   sqlite3_stmt *stmt = plugin->expire_peerstoredata;
170
171   if (SQLITE_OK !=
172       sqlite3_bind_int64 (stmt, 1, (sqlite3_uint64) now.abs_value_us))
173   {
174     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
175                 "sqlite3_bind");
176   }
177   else if (SQLITE_DONE != sqlite3_step (stmt))
178   {
179     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
180                 "sqlite3_step");
181   }
182   if (SQLITE_OK != sqlite3_reset (stmt))
183   {
184     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
185                 "sqlite3_reset");
186     return 0;
187   }
188   return sqlite3_changes (plugin->dbh);
189 }
190
191
192 /**
193  * Iterate over the records given an optional peer id
194  * and/or key.
195  *
196  * @param cls closure (internal context for the plugin)
197  * @param sub_system name of sub system
198  * @param peer Peer identity (can be NULL)
199  * @param key entry key string (can be NULL)
200  * @param iter function to call with the result
201  * @param iter_cls closure for @a iter
202  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
203  */
204 static int
205 peerstore_sqlite_iterate_records (void *cls, const char *sub_system,
206                                   const struct GNUNET_PeerIdentity *peer,
207                                   const char *key,
208                                   GNUNET_PEERSTORE_Processor iter,
209                                   void *iter_cls)
210 {
211   struct Plugin *plugin = cls;
212   sqlite3_stmt *stmt;
213   int err = 0;
214   int sret;
215   struct GNUNET_PEERSTORE_Record *ret;
216
217   LOG (GNUNET_ERROR_TYPE_DEBUG, "Executing iterate request on sqlite db.\n");
218   if (NULL == peer && NULL == key)
219   {
220     stmt = plugin->select_peerstoredata;
221     err =
222         (SQLITE_OK !=
223          sqlite3_bind_text (stmt, 1, sub_system, strlen (sub_system) + 1,
224                             SQLITE_STATIC));
225   }
226   else if (NULL == key)
227   {
228     stmt = plugin->select_peerstoredata_by_pid;
229     err =
230         (SQLITE_OK !=
231          sqlite3_bind_text (stmt, 1, sub_system, strlen (sub_system) + 1,
232                             SQLITE_STATIC)) ||
233         (SQLITE_OK !=
234          sqlite3_bind_blob (stmt, 2, peer, sizeof (struct GNUNET_PeerIdentity),
235                             SQLITE_STATIC));
236   }
237   else if (NULL == peer)
238   {
239     stmt = plugin->select_peerstoredata_by_key;
240     err =
241         (SQLITE_OK !=
242          sqlite3_bind_text (stmt, 1, sub_system, strlen (sub_system) + 1,
243                             SQLITE_STATIC)) ||
244         (SQLITE_OK !=
245          sqlite3_bind_text (stmt, 2, key, strlen (key) + 1, SQLITE_STATIC));
246   }
247   else
248   {
249     stmt = plugin->select_peerstoredata_by_all;
250     err =
251         (SQLITE_OK !=
252          sqlite3_bind_text (stmt, 1, sub_system, strlen (sub_system) + 1,
253                             SQLITE_STATIC)) ||
254         (SQLITE_OK !=
255          sqlite3_bind_blob (stmt, 2, peer, sizeof (struct GNUNET_PeerIdentity),
256                             SQLITE_STATIC)) ||
257         (SQLITE_OK !=
258          sqlite3_bind_text (stmt, 3, key, strlen (key) + 1, SQLITE_STATIC));
259   }
260
261   if (err)
262   {
263     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
264                 "sqlite3_bind_XXXX");
265     if (SQLITE_OK != sqlite3_reset (stmt))
266       LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
267                   "sqlite3_reset");
268     return GNUNET_SYSERR;
269   }
270   while (SQLITE_ROW == (sret = sqlite3_step (stmt)))
271   {
272     LOG (GNUNET_ERROR_TYPE_DEBUG, "Returning a matched record.\n");
273     ret = GNUNET_new (struct GNUNET_PEERSTORE_Record);
274
275     ret->sub_system = (char *) sqlite3_column_text (stmt, 0);
276     ret->peer = (struct GNUNET_PeerIdentity *) sqlite3_column_blob (stmt, 1);
277     ret->key = (char *) sqlite3_column_text (stmt, 2);
278     ret->value = (void *) sqlite3_column_blob (stmt, 3);
279     ret->value_size = sqlite3_column_bytes (stmt, 3);
280     ret->expiry = GNUNET_new (struct GNUNET_TIME_Absolute);
281
282     ret->expiry->abs_value_us = (uint64_t) sqlite3_column_int64 (stmt, 4);
283     if (NULL != iter)
284       iter (iter_cls, ret, NULL);
285     GNUNET_free (ret->expiry);
286     GNUNET_free (ret);
287   }
288   if (SQLITE_DONE != sret)
289   {
290     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite_step");
291     err = 1;
292   }
293   if (SQLITE_OK != sqlite3_reset (stmt))
294   {
295     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
296                 "sqlite3_reset");
297     err = 1;
298   }
299   if (err)
300     return GNUNET_SYSERR;
301   return GNUNET_OK;
302 }
303
304
305 /**
306  * Store a record in the peerstore.
307  * Key is the combination of sub system and peer identity.
308  * One key can store multiple values.
309  *
310  * @param cls closure (internal context for the plugin)
311  * @param sub_system name of the GNUnet sub system responsible
312  * @param peer peer identity
313  * @param key record key string
314  * @param value value to be stored
315  * @param size size of value to be stored
316  * @param expiry absolute time after which the record is (possibly) deleted
317  * @param options options related to the store operation
318  * @return #GNUNET_OK on success, else #GNUNET_SYSERR
319  */
320 static int
321 peerstore_sqlite_store_record (void *cls, const char *sub_system,
322                                const struct GNUNET_PeerIdentity *peer,
323                                const char *key, const void *value, size_t size,
324                                struct GNUNET_TIME_Absolute expiry,
325                                enum GNUNET_PEERSTORE_StoreOption options)
326 {
327   struct Plugin *plugin = cls;
328   sqlite3_stmt *stmt = plugin->insert_peerstoredata;
329
330   if (GNUNET_PEERSTORE_STOREOPTION_REPLACE == options)
331   {
332     peerstore_sqlite_delete_records (cls, sub_system, peer, key);
333   }
334   if (SQLITE_OK !=
335       sqlite3_bind_text (stmt, 1, sub_system, strlen (sub_system) + 1,
336                          SQLITE_STATIC) ||
337       SQLITE_OK != sqlite3_bind_blob (stmt, 2, peer,
338                                       sizeof (struct GNUNET_PeerIdentity),
339                                       SQLITE_STATIC) ||
340       SQLITE_OK != sqlite3_bind_text (stmt, 3, key, strlen (key) + 1,
341                                       SQLITE_STATIC) ||
342       SQLITE_OK != sqlite3_bind_blob (stmt, 4, value, size, SQLITE_STATIC) ||
343       SQLITE_OK != sqlite3_bind_int64 (stmt, 5,
344                                        (sqlite3_uint64) expiry.abs_value_us))
345     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
346                 "sqlite3_bind");
347   else if (SQLITE_DONE != sqlite3_step (stmt))
348   {
349     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
350                 "sqlite3_step");
351   }
352   if (SQLITE_OK != sqlite3_reset (stmt))
353   {
354     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
355                 "sqlite3_reset");
356     return GNUNET_SYSERR;
357   }
358   return GNUNET_OK;
359 }
360
361
362 /**
363  * @brief Prepare a SQL statement
364  *
365  * @param dbh handle to the database
366  * @param sql SQL statement, UTF-8 encoded
367  * @return 0 on success
368  */
369 static int
370 sql_exec (sqlite3 * dbh, const char *sql)
371 {
372   int result;
373
374   result = sqlite3_exec (dbh, sql, NULL, NULL, NULL);
375   LOG (GNUNET_ERROR_TYPE_DEBUG, "Executed `%s' / %d\n", sql, result);
376   if (result != SQLITE_OK)
377     LOG (GNUNET_ERROR_TYPE_ERROR, _("Error executing SQL query: %s\n  %s\n"),
378          sqlite3_errmsg (dbh), sql);
379   return result;
380 }
381
382
383 /**
384  * @brief Prepare a SQL statement
385  *
386  * @param dbh handle to the database
387  * @param sql SQL statement, UTF-8 encoded
388  * @param stmt set to the prepared statement
389  * @return 0 on success
390  */
391 static int
392 sql_prepare (sqlite3 * dbh, const char *sql, sqlite3_stmt ** stmt)
393 {
394   char *tail;
395   int result;
396
397   result =
398       sqlite3_prepare_v2 (dbh, sql, strlen (sql), stmt, (const char **) &tail);
399   LOG (GNUNET_ERROR_TYPE_DEBUG, "Prepared `%s' / %p: %d\n", sql, *stmt, result);
400   if (result != SQLITE_OK)
401     LOG (GNUNET_ERROR_TYPE_ERROR, _("Error preparing SQL query: %s\n  %s\n"),
402          sqlite3_errmsg (dbh), sql);
403   return result;
404 }
405
406
407 /**
408  * sqlite3 custom function for comparison of uint64_t values
409  * since it is not supported by default
410  */
411 void
412 sqlite3_lessthan (sqlite3_context * ctx, int dummy, sqlite3_value ** values)
413 {
414   uint64_t v1;
415   uint64_t v2;
416
417   v1 = (uint64_t) sqlite3_value_int64 (values[0]);
418   v2 = (uint64_t) sqlite3_value_int64 (values[1]);
419   sqlite3_result_int (ctx, v1 < v2);
420 }
421
422
423 /**
424  * Initialize the database connections and associated
425  * data structures (create tables and indices
426  * as needed as well).
427  *
428  * @param plugin the plugin context (state for this module)
429  * @return GNUNET_OK on success
430  */
431 static int
432 database_setup (struct Plugin *plugin)
433 {
434   char *filename;
435
436   if (GNUNET_OK !=
437       GNUNET_CONFIGURATION_get_value_filename (plugin->cfg, "peerstore-sqlite",
438                                                "FILENAME", &filename))
439   {
440     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, "peerstore-sqlite",
441                                "FILENAME");
442     return GNUNET_SYSERR;
443   }
444   if (GNUNET_OK != GNUNET_DISK_file_test (filename))
445   {
446     if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (filename))
447     {
448       GNUNET_break (0);
449       GNUNET_free (filename);
450       return GNUNET_SYSERR;
451     }
452   }
453   /* filename should be UTF-8-encoded. If it isn't, it's a bug */
454   plugin->fn = filename;
455   /* Open database and precompile statements */
456   if (SQLITE_OK != sqlite3_open (plugin->fn, &plugin->dbh))
457   {
458     LOG (GNUNET_ERROR_TYPE_ERROR, _("Unable to initialize SQLite: %s.\n"),
459          sqlite3_errmsg (plugin->dbh));
460     return GNUNET_SYSERR;
461   }
462   sql_exec (plugin->dbh, "PRAGMA temp_store=MEMORY");
463   sql_exec (plugin->dbh, "PRAGMA synchronous=OFF");
464   sql_exec (plugin->dbh, "PRAGMA legacy_file_format=OFF");
465   sql_exec (plugin->dbh, "PRAGMA auto_vacuum=INCREMENTAL");
466   sql_exec (plugin->dbh, "PRAGMA encoding=\"UTF-8\"");
467   sql_exec (plugin->dbh, "PRAGMA count_changes=OFF");
468   sql_exec (plugin->dbh, "PRAGMA page_size=4096");
469   sqlite3_busy_timeout (plugin->dbh, BUSY_TIMEOUT_MS);
470   /* Create tables */
471   sql_exec (plugin->dbh,
472             "CREATE TABLE IF NOT EXISTS peerstoredata (\n"
473             "  sub_system TEXT NOT NULL,\n" "  peer_id BLOB NOT NULL,\n"
474             "  key TEXT NOT NULL,\n" "  value BLOB NULL,\n"
475             "  expiry sqlite3_uint64 NOT NULL" ");");
476   sqlite3_create_function (plugin->dbh, "UINT64_LT", 2, SQLITE_UTF8, NULL,
477                            &sqlite3_lessthan, NULL, NULL);
478   /* Create Indices */
479   if (SQLITE_OK !=
480       sqlite3_exec (plugin->dbh,
481                     "CREATE INDEX IF NOT EXISTS peerstoredata_key_index ON peerstoredata (sub_system, peer_id, key)",
482                     NULL, NULL, NULL))
483   {
484     LOG (GNUNET_ERROR_TYPE_ERROR, _("Unable to create indices: %s.\n"),
485          sqlite3_errmsg (plugin->dbh));
486     return GNUNET_SYSERR;
487   }
488   /* Prepare statements */
489
490   sql_prepare (plugin->dbh,
491                "INSERT INTO peerstoredata (sub_system, peer_id, key, value, expiry) VALUES (?,?,?,?,?);",
492                &plugin->insert_peerstoredata);
493   sql_prepare (plugin->dbh,
494                "SELECT * FROM peerstoredata" " WHERE sub_system = ?",
495                &plugin->select_peerstoredata);
496   sql_prepare (plugin->dbh,
497                "SELECT * FROM peerstoredata" " WHERE sub_system = ?"
498                " AND peer_id = ?", &plugin->select_peerstoredata_by_pid);
499   sql_prepare (plugin->dbh,
500                "SELECT * FROM peerstoredata" " WHERE sub_system = ?"
501                " AND key = ?", &plugin->select_peerstoredata_by_key);
502   sql_prepare (plugin->dbh,
503                "SELECT * FROM peerstoredata" " WHERE sub_system = ?"
504                " AND peer_id = ?" " AND key = ?",
505                &plugin->select_peerstoredata_by_all);
506   sql_prepare (plugin->dbh,
507                "DELETE FROM peerstoredata" " WHERE UINT64_LT(expiry, ?)",
508                &plugin->expire_peerstoredata);
509   sql_prepare (plugin->dbh,
510                "DELETE FROM peerstoredata" " WHERE sub_system = ?"
511                " AND peer_id = ?" " AND key = ?",
512                &plugin->delete_peerstoredata);
513   return GNUNET_OK;
514 }
515
516
517 /**
518  * Shutdown database connection and associate data
519  * structures.
520  * @param plugin the plugin context (state for this module)
521  */
522 static void
523 database_shutdown (struct Plugin *plugin)
524 {
525   int result;
526   sqlite3_stmt *stmt;
527
528   while (NULL != (stmt = sqlite3_next_stmt (plugin->dbh, NULL)))
529   {
530     result = sqlite3_finalize (stmt);
531     if (SQLITE_OK != result)
532       LOG (GNUNET_ERROR_TYPE_WARNING, "Failed to close statement %p: %d\n",
533            stmt, result);
534   }
535   if (SQLITE_OK != sqlite3_close (plugin->dbh))
536     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close");
537   GNUNET_free_non_null (plugin->fn);
538 }
539
540
541 /**
542  * Entry point for the plugin.
543  *
544  * @param cls The struct GNUNET_CONFIGURATION_Handle.
545  * @return NULL on error, otherwise the plugin context
546  */
547 void *
548 libgnunet_plugin_peerstore_sqlite_init (void *cls)
549 {
550   static struct Plugin plugin;
551   const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
552   struct GNUNET_PEERSTORE_PluginFunctions *api;
553
554   if (NULL != plugin.cfg)
555     return NULL;                /* can only initialize once! */
556   memset (&plugin, 0, sizeof (struct Plugin));
557   plugin.cfg = cfg;
558   if (GNUNET_OK != database_setup (&plugin))
559   {
560     database_shutdown (&plugin);
561     return NULL;
562   }
563   api = GNUNET_new (struct GNUNET_PEERSTORE_PluginFunctions);
564   api->cls = &plugin;
565   api->store_record = &peerstore_sqlite_store_record;
566   api->iterate_records = &peerstore_sqlite_iterate_records;
567   api->expire_records = &peerstore_sqlite_expire_records;
568   LOG (GNUNET_ERROR_TYPE_DEBUG, "Sqlite plugin is running\n");
569   return api;
570 }
571
572
573 /**
574  * Exit point from the plugin.
575  *
576  * @param cls The plugin context (as returned by "init")
577  * @return Always NULL
578  */
579 void *
580 libgnunet_plugin_peerstore_sqlite_done (void *cls)
581 {
582   struct GNUNET_PEERSTORE_PluginFunctions *api = cls;
583   struct Plugin *plugin = api->cls;
584
585   database_shutdown (plugin);
586   plugin->cfg = NULL;
587   GNUNET_free (api);
588   LOG (GNUNET_ERROR_TYPE_DEBUG, "Sqlite plugin is finished\n");
589   return NULL;
590 }
591
592 /* end of plugin_peerstore_sqlite.c */