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