PEERSTORE store function
[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
82 /**
83  * Store a record in the peerstore.
84  * Key is the combination of sub system and peer identity.
85  * One key can store multiple values.
86  *
87  * @param cls closure (internal context for the plugin)
88  * @param peer peer identity
89  * @param sub_system name of the GNUnet sub system responsible
90  * @param value value to be stored
91  * @param size size of value to be stored
92  * @return #GNUNET_OK on success, else #GNUNET_SYSERR
93  */
94 static int
95 peerstore_sqlite_store_record (void *cls,
96     const struct GNUNET_PeerIdentity *peer,
97     const char *sub_system,
98     const void *value,
99     size_t size)
100 {
101   struct Plugin *plugin = cls;
102   sqlite3_stmt *stmt = plugin->insert_peerstoredata;
103
104   //FIXME: check if value exists with the same key first
105
106   if(SQLITE_OK != sqlite3_bind_blob(stmt, 2, peer, sizeof(struct GNUNET_PeerIdentity), SQLITE_STATIC)
107       || SQLITE_OK != sqlite3_bind_text(stmt, 1, sub_system, strlen(sub_system) + 1, SQLITE_STATIC)
108       || SQLITE_OK != sqlite3_bind_blob(stmt, 3, value, size, SQLITE_STATIC))
109     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
110                     "sqlite3_bind");
111   else if (SQLITE_DONE != sqlite3_step (stmt))
112   {
113     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
114                 "sqlite3_step");
115   }
116   if (SQLITE_OK != sqlite3_reset (stmt))
117   {
118     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
119                 "sqlite3_reset");
120     return GNUNET_SYSERR;
121   }
122
123   return GNUNET_OK;
124 }
125
126
127 /**
128  * @brief Prepare a SQL statement
129  *
130  * @param dbh handle to the database
131  * @param sql SQL statement, UTF-8 encoded
132  * @return 0 on success
133  */
134 static int
135 sql_exec (sqlite3 *dbh, const char *sql)
136 {
137   int result;
138
139   result = sqlite3_exec (dbh, sql, NULL, NULL, NULL);
140   LOG (GNUNET_ERROR_TYPE_DEBUG,
141        "Executed `%s' / %d\n", sql, result);
142   if (result != SQLITE_OK)
143     LOG (GNUNET_ERROR_TYPE_ERROR,
144    _("Error executing SQL query: %s\n  %s\n"),
145    sqlite3_errmsg (dbh), sql);
146   return result;
147 }
148
149 /**
150  * @brief Prepare a SQL statement
151  *
152  * @param dbh handle to the database
153  * @param sql SQL statement, UTF-8 encoded
154  * @param stmt set to the prepared statement
155  * @return 0 on success
156  */
157 static int
158 sql_prepare (sqlite3 *dbh, const char *sql, sqlite3_stmt **stmt)
159 {
160   char *tail;
161   int result;
162
163   result = sqlite3_prepare_v2 (dbh, sql, strlen (sql), stmt,
164                                (const char **) &tail);
165   LOG (GNUNET_ERROR_TYPE_DEBUG,
166        "Prepared `%s' / %p: %d\n", sql, *stmt, result);
167   if (result != SQLITE_OK)
168     LOG (GNUNET_ERROR_TYPE_ERROR,
169    _("Error preparing SQL query: %s\n  %s\n"),
170    sqlite3_errmsg (dbh), sql);
171   return result;
172 }
173
174 /**
175  * Initialize the database connections and associated
176  * data structures (create tables and indices
177  * as needed as well).
178  *
179  * @param plugin the plugin context (state for this module)
180  * @return GNUNET_OK on success
181  */
182 static int
183 database_setup (struct Plugin *plugin)
184 {
185   char *filename;
186
187   if (GNUNET_OK !=
188       GNUNET_CONFIGURATION_get_value_filename (plugin->cfg, "peerstore-sqlite",
189                                                "FILENAME", &filename))
190   {
191     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
192              "peerstore-sqlite", "FILENAME");
193     return GNUNET_SYSERR;
194   }
195   if (GNUNET_OK != GNUNET_DISK_file_test (filename))
196   {
197     if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (filename))
198     {
199       GNUNET_break (0);
200       GNUNET_free (filename);
201       return GNUNET_SYSERR;
202     }
203   }
204   /* filename should be UTF-8-encoded. If it isn't, it's a bug */
205   plugin->fn = filename;
206
207   /* Open database and precompile statements */
208   if (SQLITE_OK != sqlite3_open (plugin->fn, &plugin->dbh))
209   {
210     LOG (GNUNET_ERROR_TYPE_ERROR,
211    _("Unable to initialize SQLite: %s.\n"),
212    sqlite3_errmsg (plugin->dbh));
213     return GNUNET_SYSERR;
214   }
215
216   sql_exec (plugin->dbh, "PRAGMA temp_store=MEMORY");
217   sql_exec (plugin->dbh, "PRAGMA synchronous=NORMAL");
218   sql_exec (plugin->dbh, "PRAGMA legacy_file_format=OFF");
219   sql_exec (plugin->dbh, "PRAGMA auto_vacuum=INCREMENTAL");
220   sql_exec (plugin->dbh, "PRAGMA encoding=\"UTF-8\"");
221   sql_exec (plugin->dbh, "PRAGMA count_changes=OFF");
222   sql_exec (plugin->dbh, "PRAGMA page_size=4096");
223
224   sqlite3_busy_timeout (plugin->dbh, BUSY_TIMEOUT_MS);
225
226   /* Create tables */
227
228   sql_exec (plugin->dbh,
229             "CREATE TABLE IF NOT EXISTS peerstoredata (\n"
230             "  peer_id BLOB NOT NULL,\n"
231             "  sub_system TEXT NOT NULL,\n"
232             "  value BLOB NULL"
233             ");");
234
235   /* Prepare statements */
236
237   sql_prepare (plugin->dbh,
238                "INSERT INTO peerstoredata (peer_id, sub_system, value) VALUES (?,?,?);",
239                &plugin->insert_peerstoredata);
240
241   return GNUNET_OK;
242 }
243
244 /**
245  * Shutdown database connection and associate data
246  * structures.
247  * @param plugin the plugin context (state for this module)
248  */
249 static void
250 database_shutdown (struct Plugin *plugin)
251 {
252   int result;
253   sqlite3_stmt *stmt;
254   while (NULL != (stmt = sqlite3_next_stmt (plugin->dbh, NULL)))
255   {
256     result = sqlite3_finalize (stmt);
257     if (SQLITE_OK != result)
258       LOG (GNUNET_ERROR_TYPE_WARNING,
259            "Failed to close statement %p: %d\n", stmt, result);
260   }
261   if (SQLITE_OK != sqlite3_close (plugin->dbh))
262     LOG_SQLITE (plugin, GNUNET_ERROR_TYPE_ERROR, "sqlite3_close");
263
264   GNUNET_free_non_null (plugin->fn);
265 }
266
267 /**
268  * Entry point for the plugin.
269  *
270  * @param cls The struct GNUNET_CONFIGURATION_Handle.
271  * @return NULL on error, otherwise the plugin context
272  */
273 void *
274 libgnunet_plugin_peerstore_sqlite_init (void *cls)
275 {
276   static struct Plugin plugin;
277   const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
278   struct GNUNET_PEERSTORE_PluginFunctions *api;
279
280   if (NULL != plugin.cfg)
281     return NULL;                /* can only initialize once! */
282   memset (&plugin, 0, sizeof (struct Plugin));
283   plugin.cfg = cfg;
284   if (GNUNET_OK != database_setup (&plugin))
285   {
286     database_shutdown (&plugin);
287     return NULL;
288   }
289   api = GNUNET_new (struct GNUNET_PEERSTORE_PluginFunctions);
290   api->cls = &plugin;
291   api->store_record = &peerstore_sqlite_store_record;
292   LOG(GNUNET_ERROR_TYPE_DEBUG, "Sqlite plugin is running\n");
293   return api;
294 }
295
296 /**
297  * Exit point from the plugin.
298  *
299  * @param cls The plugin context (as returned by "init")
300  * @return Always NULL
301  */
302 void *
303 libgnunet_plugin_peerstore_sqlite_done (void *cls)
304 {
305   struct GNUNET_PEERSTORE_PluginFunctions *api = cls;
306   struct Plugin *plugin = api->cls;
307
308   database_shutdown (plugin);
309   plugin->cfg = NULL;
310   GNUNET_free (api);
311   LOG (GNUNET_ERROR_TYPE_DEBUG, "Sqlite plugin is finished\n");
312   return NULL;
313
314 }
315
316 /* end of plugin_peerstore_sqlite.c */