1ae8301b2a5c418270bb8f16dc57095d15a37dda
[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
102 /**
103  * Iterate over the records given an optional peer id
104  * and/or key.
105  *
106  * @param cls closure (internal context for the plugin)
107  * @param sub_system name of sub system
108  * @param peer Peer identity (can be NULL)
109  * @param key entry key string (can be NULL)
110  * @param iter function to call with the result
111  * @param iter_cls closure for @a iter
112  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
113  */
114 static int
115 peerstore_sqlite_iterate_records (void *cls,
116     const char *sub_system,
117     const struct GNUNET_PeerIdentity *peer,
118     const char *key,
119     GNUNET_PEERSTORE_Processor iter, void *iter_cls)
120 {
121   struct Plugin *plugin = cls;
122   sqlite3_stmt *stmt;
123   int err = 0;
124   int sret;
125   struct GNUNET_PEERSTORE_Record *ret;
126
127   if(NULL == peer && NULL == key)
128   {
129     stmt = plugin->select_peerstoredata;
130     err = (SQLITE_OK != sqlite3_bind_text(stmt, 1, sub_system, strlen(sub_system) + 1, SQLITE_STATIC));
131   }
132   else if(NULL == key)
133   {
134     stmt = plugin->select_peerstoredata_by_pid;
135     err = (SQLITE_OK != sqlite3_bind_text(stmt, 1, sub_system, strlen(sub_system) + 1, SQLITE_STATIC))
136         || (SQLITE_OK != sqlite3_bind_blob(stmt, 2, peer, sizeof(struct GNUNET_PeerIdentity), SQLITE_STATIC));
137   }
138   else if(NULL == peer)
139   {
140     stmt = plugin->select_peerstoredata_by_key;
141     err = (SQLITE_OK != sqlite3_bind_text(stmt, 1, sub_system, strlen(sub_system) + 1, SQLITE_STATIC))
142         || (SQLITE_OK != sqlite3_bind_text(stmt, 3, key, strlen(key) + 1, SQLITE_STATIC));
143   }
144   else
145   {
146     stmt = plugin->select_peerstoredata_by_all;
147     err = (SQLITE_OK != sqlite3_bind_text(stmt, 1, sub_system, strlen(sub_system) + 1, SQLITE_STATIC))
148             || (SQLITE_OK != sqlite3_bind_blob(stmt, 2, peer, sizeof(struct GNUNET_PeerIdentity), SQLITE_STATIC))
149             || (SQLITE_OK != sqlite3_bind_text(stmt, 3, key, strlen(key) + 1, SQLITE_STATIC));
150   }
151
152   if (err)
153   {
154     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
155     "sqlite3_bind_XXXX");
156     if (SQLITE_OK != sqlite3_reset (stmt))
157       LOG_SQLITE (plugin,
158       GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
159       "sqlite3_reset");
160     return GNUNET_SYSERR;
161   }
162   while (SQLITE_ROW == (sret = sqlite3_step (stmt)))
163   {
164     ret = GNUNET_new(struct GNUNET_PEERSTORE_Record);
165     ret->sub_system = (char *)sqlite3_column_text(stmt, 0);
166     ret->peer = (struct GNUNET_PeerIdentity *)sqlite3_column_blob(stmt, 1);
167     ret->key = (char *)sqlite3_column_text(stmt, 2);
168     ret->value = (void *)sqlite3_column_blob(stmt, 3);
169     ret->value_size = sqlite3_column_bytes(stmt, 3);
170     ret->expiry = GNUNET_new(struct GNUNET_TIME_Absolute);
171     ret->expiry->abs_value_us = (uint64_t)sqlite3_column_int64(stmt, 4);
172     if (NULL != iter)
173       iter (iter_cls,
174           ret,
175           NULL);
176   }
177   if (SQLITE_DONE != sret)
178   {
179     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite_step");
180     err = 1;
181   }
182   if (SQLITE_OK != sqlite3_reset (stmt))
183   {
184     LOG_SQLITE (plugin,
185     GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
186     "sqlite3_reset");
187     err = 1;
188   }
189   if(err)
190     return GNUNET_SYSERR;
191   return GNUNET_OK;
192 }
193
194 /**
195  * Store a record in the peerstore.
196  * Key is the combination of sub system and peer identity.
197  * One key can store multiple values.
198  *
199  * @param cls closure (internal context for the plugin)
200  * @param peer peer identity
201  * @param sub_system name of the GNUnet sub system responsible
202  * @param value value to be stored
203  * @param size size of value to be stored
204  * @return #GNUNET_OK on success, else #GNUNET_SYSERR
205  */
206 static int
207 peerstore_sqlite_store_record(void *cls,
208     const char *sub_system,
209     const struct GNUNET_PeerIdentity *peer,
210     const char *key,
211     const void *value,
212     size_t size,
213     struct GNUNET_TIME_Absolute expiry)
214 {
215   struct Plugin *plugin = cls;
216   sqlite3_stmt *stmt = plugin->insert_peerstoredata;
217
218   //FIXME: check if value exists with the same key first
219
220   if(SQLITE_OK != sqlite3_bind_text(stmt, 1, sub_system, strlen(sub_system) + 1, SQLITE_STATIC)
221       || SQLITE_OK != sqlite3_bind_blob(stmt, 2, peer, sizeof(struct GNUNET_PeerIdentity), SQLITE_STATIC)
222       || SQLITE_OK != sqlite3_bind_text(stmt, 3, key, strlen(key) + 1, SQLITE_STATIC)
223       || SQLITE_OK != sqlite3_bind_blob(stmt, 4, value, size, SQLITE_STATIC)
224       || SQLITE_OK != sqlite3_bind_int64(stmt, 5, (sqlite3_int64)expiry.abs_value_us))
225     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
226                     "sqlite3_bind");
227   else if (SQLITE_DONE != sqlite3_step (stmt))
228   {
229     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
230                 "sqlite3_step");
231   }
232   if (SQLITE_OK != sqlite3_reset (stmt))
233   {
234     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
235                 "sqlite3_reset");
236     return GNUNET_SYSERR;
237   }
238
239   return GNUNET_OK;
240 }
241
242
243 /**
244  * @brief Prepare a SQL statement
245  *
246  * @param dbh handle to the database
247  * @param sql SQL statement, UTF-8 encoded
248  * @return 0 on success
249  */
250 static int
251 sql_exec (sqlite3 *dbh, const char *sql)
252 {
253   int result;
254
255   result = sqlite3_exec (dbh, sql, NULL, NULL, NULL);
256   LOG (GNUNET_ERROR_TYPE_DEBUG,
257        "Executed `%s' / %d\n", sql, result);
258   if (result != SQLITE_OK)
259     LOG (GNUNET_ERROR_TYPE_ERROR,
260    _("Error executing SQL query: %s\n  %s\n"),
261    sqlite3_errmsg (dbh), sql);
262   return result;
263 }
264
265 /**
266  * @brief Prepare a SQL statement
267  *
268  * @param dbh handle to the database
269  * @param sql SQL statement, UTF-8 encoded
270  * @param stmt set to the prepared statement
271  * @return 0 on success
272  */
273 static int
274 sql_prepare (sqlite3 *dbh, const char *sql, sqlite3_stmt **stmt)
275 {
276   char *tail;
277   int result;
278
279   result = sqlite3_prepare_v2 (dbh, sql, strlen (sql), stmt,
280                                (const char **) &tail);
281   LOG (GNUNET_ERROR_TYPE_DEBUG,
282        "Prepared `%s' / %p: %d\n", sql, *stmt, result);
283   if (result != SQLITE_OK)
284     LOG (GNUNET_ERROR_TYPE_ERROR,
285    _("Error preparing SQL query: %s\n  %s\n"),
286    sqlite3_errmsg (dbh), sql);
287   return result;
288 }
289
290 /**
291  * Initialize the database connections and associated
292  * data structures (create tables and indices
293  * as needed as well).
294  *
295  * @param plugin the plugin context (state for this module)
296  * @return GNUNET_OK on success
297  */
298 static int
299 database_setup (struct Plugin *plugin)
300 {
301   char *filename;
302
303   if (GNUNET_OK !=
304       GNUNET_CONFIGURATION_get_value_filename (plugin->cfg, "peerstore-sqlite",
305                                                "FILENAME", &filename))
306   {
307     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
308              "peerstore-sqlite", "FILENAME");
309     return GNUNET_SYSERR;
310   }
311   if (GNUNET_OK != GNUNET_DISK_file_test (filename))
312   {
313     if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (filename))
314     {
315       GNUNET_break (0);
316       GNUNET_free (filename);
317       return GNUNET_SYSERR;
318     }
319   }
320   /* filename should be UTF-8-encoded. If it isn't, it's a bug */
321   plugin->fn = filename;
322
323   /* Open database and precompile statements */
324   if (SQLITE_OK != sqlite3_open (plugin->fn, &plugin->dbh))
325   {
326     LOG (GNUNET_ERROR_TYPE_ERROR,
327    _("Unable to initialize SQLite: %s.\n"),
328    sqlite3_errmsg (plugin->dbh));
329     return GNUNET_SYSERR;
330   }
331
332   sql_exec (plugin->dbh, "PRAGMA temp_store=MEMORY");
333   sql_exec (plugin->dbh, "PRAGMA synchronous=NORMAL");
334   sql_exec (plugin->dbh, "PRAGMA legacy_file_format=OFF");
335   sql_exec (plugin->dbh, "PRAGMA auto_vacuum=INCREMENTAL");
336   sql_exec (plugin->dbh, "PRAGMA encoding=\"UTF-8\"");
337   sql_exec (plugin->dbh, "PRAGMA count_changes=OFF");
338   sql_exec (plugin->dbh, "PRAGMA page_size=4096");
339
340   sqlite3_busy_timeout (plugin->dbh, BUSY_TIMEOUT_MS);
341
342   /* Create tables */
343
344   sql_exec (plugin->dbh,
345       "CREATE TABLE IF NOT EXISTS peerstoredata (\n"
346       "  sub_system TEXT NOT NULL,\n"
347       "  peer_id BLOB NOT NULL,\n"
348       "  key TEXT NOT NULL,\n"
349       "  value BLOB NULL,\n"
350       "  expiry INTEGER NOT NULL"
351       ");");
352
353   /* Prepare statements */
354
355   sql_prepare (plugin->dbh,
356       "INSERT INTO peerstoredata (sub_system, peer_id, key, value, expiry) VALUES (?,?,?,?,?);",
357       &plugin->insert_peerstoredata);
358   sql_prepare(plugin->dbh,
359       "SELECT * FROM peerstoredata"
360       " WHERE sub_system = ?",
361       &plugin->select_peerstoredata);
362   sql_prepare(plugin->dbh,
363       "SELECT * FROM peerstoredata"
364       " WHERE sub_system = ?"
365       " AND peer_id = ?",
366       &plugin->select_peerstoredata_by_pid);
367   sql_prepare(plugin->dbh,
368       "SELECT * FROM peerstoredata"
369       " WHERE sub_system = ?"
370       " AND key = ?",
371       &plugin->select_peerstoredata_by_key);
372   sql_prepare(plugin->dbh,
373       "SELECT * FROM peerstoredata"
374       " WHERE sub_system = ?"
375       " AND peer_id = ?"
376       " AND key = ?",
377       &plugin->select_peerstoredata_by_all);
378
379   return GNUNET_OK;
380 }
381
382 /**
383  * Shutdown database connection and associate data
384  * structures.
385  * @param plugin the plugin context (state for this module)
386  */
387 static void
388 database_shutdown (struct Plugin *plugin)
389 {
390   int result;
391   sqlite3_stmt *stmt;
392   while (NULL != (stmt = sqlite3_next_stmt (plugin->dbh, NULL)))
393   {
394     result = sqlite3_finalize (stmt);
395     if (SQLITE_OK != result)
396       LOG (GNUNET_ERROR_TYPE_WARNING,
397            "Failed to close statement %p: %d\n", stmt, result);
398   }
399   if (SQLITE_OK != sqlite3_close (plugin->dbh))
400     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close");
401
402   GNUNET_free_non_null (plugin->fn);
403 }
404
405 /**
406  * Entry point for the plugin.
407  *
408  * @param cls The struct GNUNET_CONFIGURATION_Handle.
409  * @return NULL on error, otherwise the plugin context
410  */
411 void *
412 libgnunet_plugin_peerstore_sqlite_init (void *cls)
413 {
414   static struct Plugin plugin;
415   const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
416   struct GNUNET_PEERSTORE_PluginFunctions *api;
417
418   if (NULL != plugin.cfg)
419     return NULL;                /* can only initialize once! */
420   memset (&plugin, 0, sizeof (struct Plugin));
421   plugin.cfg = cfg;
422   if (GNUNET_OK != database_setup (&plugin))
423   {
424     database_shutdown (&plugin);
425     return NULL;
426   }
427   api = GNUNET_new (struct GNUNET_PEERSTORE_PluginFunctions);
428   api->cls = &plugin;
429   api->store_record = &peerstore_sqlite_store_record;
430   api->iterate_records = &peerstore_sqlite_iterate_records;
431   LOG(GNUNET_ERROR_TYPE_DEBUG, "Sqlite plugin is running\n");
432   return api;
433 }
434
435 /**
436  * Exit point from the plugin.
437  *
438  * @param cls The plugin context (as returned by "init")
439  * @return Always NULL
440  */
441 void *
442 libgnunet_plugin_peerstore_sqlite_done (void *cls)
443 {
444   struct GNUNET_PEERSTORE_PluginFunctions *api = cls;
445   struct Plugin *plugin = api->cls;
446
447   database_shutdown (plugin);
448   plugin->cfg = NULL;
449   GNUNET_free (api);
450   LOG (GNUNET_ERROR_TYPE_DEBUG, "Sqlite plugin is finished\n");
451   return NULL;
452
453 }
454
455 /* end of plugin_peerstore_sqlite.c */