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