2 This file is part of GNUnet
3 (C) 2009, 2010, 2011 Christian Grothoff (and other contributing authors)
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.
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.
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.
22 * @file datastore/plugin_datastore_mysql.c
23 * @brief mysql-based datastore backend
24 * @author Igor Wronsky
25 * @author Christian Grothoff
27 * NOTE: This db module does NOT work with mysql prior to 4.1 since
28 * it uses prepared statements. MySQL 5.0.46 promises to fix a bug
29 * in MyISAM that is causing us grief. At the time of this writing,
30 * that version is yet to be released. In anticipation, the code
31 * will use MyISAM with 5.0.46 (and higher). If you run such a
32 * version, please run "make check" to verify that the MySQL bug
33 * was actually fixed in your version (and if not, change the
34 * code below to use MyISAM for gn071).
39 * + On up-to-date hardware where mysql can be used comfortably, this
40 * module will have better performance than the other db choices
41 * (according to our tests).
42 * + Its often possible to recover the mysql database from internal
43 * inconsistencies. The other db choices do not support repair!
45 * - Memory usage (Comment: "I have 1G and it never caused me trouble")
48 * MANUAL SETUP INSTRUCTIONS
50 * 1) in /etc/gnunet.conf, set
55 * 2) Then access mysql as root,
59 * and do the following. [You should replace $USER with the username
60 * that will be running the gnunetd process].
62 CREATE DATABASE gnunet;
63 GRANT select,insert,update,delete,create,alter,drop,create temporary tables
64 ON gnunet.* TO $USER@localhost;
65 SET PASSWORD FOR $USER@localhost=PASSWORD('$the_password_you_like');
68 * 3) In the $HOME directory of $USER, create a ".my.cnf" file
69 * with the following lines
73 password=$the_password_you_like
76 * Thats it. Note that .my.cnf file is a security risk unless its on
77 * a safe partition etc. The $HOME/.my.cnf can of course be a symbolic
78 * link. Even greater security risk can be achieved by setting no
79 * password for $USER. Luckily $USER has only priviledges to mess
80 * up GNUnet's tables, nothing else (unless you give him more,
83 * 4) Still, perhaps you should briefly try if the DB connection
84 * works. First, login as $USER. Then use,
87 $ mysql -u $USER -p $the_password_you_like
91 * If you get the message "Database changed" it probably works.
93 * [If you get "ERROR 2002: Can't connect to local MySQL server
94 * through socket '/tmp/mysql.sock' (2)" it may be resolvable by
95 * "ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock"
96 * so there may be some additional trouble depending on your mysql setup.]
100 * - Its probably healthy to check your tables for inconsistencies
101 * every now and then.
102 * - If you get odd SEGVs on gnunetd startup, it might be that the mysql
103 * databases have been corrupted.
104 * - The tables can be verified/fixed in two ways;
105 * 1) by running mysqlcheck -A, or
106 * 2) by executing (inside of mysql using the GNUnet database):
108 mysql> REPAIR TABLE gn090;
113 * If you have problems related to the mysql module, your best
114 * friend is probably the mysql manual. The first thing to check
115 * is that mysql is basically operational, that you can connect
116 * to it, create tables, issue queries etc.
119 #include "platform.h"
120 #include "gnunet_datastore_plugin.h"
121 #include "gnunet_util_lib.h"
122 #include <mysql/mysql.h>
124 #define DEBUG_MYSQL GNUNET_NO
126 #define MAX_DATUM_SIZE 65536
129 * Maximum number of supported parameters for a prepared
130 * statement. Increase if needed.
135 * Die with an error message that indicates
136 * a failure of the command 'cmd' with the message given
137 * by strerror(errno).
139 #define DIE_MYSQL(cmd, dbh) do { GNUNET_log(GNUNET_ERROR_TYPE_ERROR, _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, mysql_error((dbh)->dbf)); abort(); } while(0);
142 * Log an error message at log-level 'level' that indicates
143 * a failure of the command 'cmd' on file 'filename'
144 * with the message given by strerror(errno).
146 #define LOG_MYSQL(level, cmd, dbh) do { GNUNET_log(level, _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, mysql_error((dbh)->dbf)); } while(0);
149 struct GNUNET_MysqlStatementHandle
151 struct GNUNET_MysqlStatementHandle *next;
153 struct GNUNET_MysqlStatementHandle *prev;
157 MYSQL_STMT *statement;
165 * Context for all functions in this plugin.
170 * Our execution environment.
172 struct GNUNET_DATASTORE_PluginEnvironment *env;
175 * Handle to talk to MySQL.
180 * We keep all prepared statements in a DLL. This is the head.
182 struct GNUNET_MysqlStatementHandle *shead;
185 * We keep all prepared statements in a DLL. This is the tail.
187 struct GNUNET_MysqlStatementHandle *stail;
190 * Filename of "my.cnf" (msyql configuration).
195 * Prepared statements.
197 #define INSERT_ENTRY "INSERT INTO gn090 (repl,type,prio,anonLevel,expire,rvalue,hash,vhash,value) VALUES (?,?,?,?,?,?,?,?,?)"
198 struct GNUNET_MysqlStatementHandle *insert_entry;
200 #define DELETE_ENTRY_BY_UID "DELETE FROM gn090 WHERE uid=?"
201 struct GNUNET_MysqlStatementHandle *delete_entry_by_uid;
203 #define COUNT_ENTRY_BY_HASH "SELECT count(*) FROM gn090 WHERE hash=?"
204 struct GNUNET_MysqlStatementHandle *count_entry_by_hash;
206 #define SELECT_ENTRY_BY_HASH "SELECT type,prio,anonLevel,expire,hash,value,uid FROM gn090 WHERE hash=? ORDER BY uid LIMIT 1 OFFSET ?"
207 struct GNUNET_MysqlStatementHandle *select_entry_by_hash;
209 #define COUNT_ENTRY_BY_HASH_AND_VHASH "SELECT count(*) FROM gn090 WHERE hash=? AND vhash=?"
210 struct GNUNET_MysqlStatementHandle *count_entry_by_hash_and_vhash;
212 #define SELECT_ENTRY_BY_HASH_AND_VHASH "SELECT type,prio,anonLevel,expire,hash,value,uid FROM gn090 WHERE hash=? AND vhash=? ORDER BY uid LIMIT 1 OFFSET ?"
213 struct GNUNET_MysqlStatementHandle *select_entry_by_hash_and_vhash;
215 #define COUNT_ENTRY_BY_HASH_AND_TYPE "SELECT count(*) FROM gn090 WHERE hash=? AND type=?"
216 struct GNUNET_MysqlStatementHandle *count_entry_by_hash_and_type;
218 #define SELECT_ENTRY_BY_HASH_AND_TYPE "SELECT type,prio,anonLevel,expire,hash,value,uid FROM gn090 WHERE hash=? AND type=? ORDER BY uid LIMIT 1 OFFSET ?"
219 struct GNUNET_MysqlStatementHandle *select_entry_by_hash_and_type;
221 #define COUNT_ENTRY_BY_HASH_VHASH_AND_TYPE "SELECT count(*) FROM gn090 WHERE hash=? AND vhash=? AND type=?"
222 struct GNUNET_MysqlStatementHandle *count_entry_by_hash_vhash_and_type;
224 #define SELECT_ENTRY_BY_HASH_VHASH_AND_TYPE "SELECT type,prio,anonLevel,expire,hash,value,uid FROM gn090 WHERE hash=? AND vhash=? AND type=? ORDER BY uid ASC LIMIT 1 OFFSET ?"
225 struct GNUNET_MysqlStatementHandle *select_entry_by_hash_vhash_and_type;
227 #define UPDATE_ENTRY "UPDATE gn090 SET prio=prio+?,expire=IF(expire>=?,expire,?) WHERE uid=?"
228 struct GNUNET_MysqlStatementHandle *update_entry;
230 #define DEC_REPL "UPDATE gn090 SET repl=GREATEST (0, repl - 1) WHERE uid=?"
231 struct GNUNET_MysqlStatementHandle *dec_repl;
233 #define SELECT_SIZE "SELECT SUM(BIT_LENGTH(value) DIV 8) FROM gn090"
234 struct GNUNET_MysqlStatementHandle *get_size;
236 #define SELECT_IT_NON_ANONYMOUS "SELECT type,prio,anonLevel,expire,hash,value,uid FROM gn090 WHERE anonLevel=0 AND type=? ORDER BY uid DESC LIMIT 1 OFFSET ?"
237 struct GNUNET_MysqlStatementHandle *zero_iter;
239 #define SELECT_IT_EXPIRATION "(SELECT type,prio,anonLevel,expire,hash,value,uid FROM gn090 WHERE expire < ? ORDER BY prio ASC LIMIT 1) "\
241 "(SELECT type,prio,anonLevel,expire,hash,value,uid FROM gn090 ORDER BY prio ASC LIMIT 1) "\
242 "ORDER BY expire ASC LIMIT 1"
243 struct GNUNET_MysqlStatementHandle *select_expiration;
245 #define SELECT_IT_REPLICATION "SELECT type,prio,anonLevel,expire,hash,value,uid FROM gn090 ORDER BY repl DESC,RAND() LIMIT 1"
246 struct GNUNET_MysqlStatementHandle *select_replication;
252 * Obtain the location of ".my.cnf".
254 * @param cfg our configuration
255 * @return NULL on error
258 get_my_cnf_path (const struct GNUNET_CONFIGURATION_Handle *cfg)
269 pw = getpwuid (getuid ());
272 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
277 GNUNET_CONFIGURATION_have_value (cfg,
278 "datastore-mysql", "CONFIG"))
280 GNUNET_assert (GNUNET_OK ==
281 GNUNET_CONFIGURATION_get_value_filename (cfg,
282 "datastore-mysql", "CONFIG", &cnffile));
283 configured = GNUNET_YES;
287 home_dir = GNUNET_strdup (pw->pw_dir);
289 home_dir = (char *) GNUNET_malloc (_MAX_PATH + 1);
290 plibc_conv_to_win_path ("~/", home_dir);
292 GNUNET_asprintf (&cnffile, "%s/.my.cnf", home_dir);
293 GNUNET_free (home_dir);
294 configured = GNUNET_NO;
296 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
297 _("Trying to use file `%s' for MySQL configuration.\n"),
299 if ((0 != STAT (cnffile, &st)) ||
300 (0 != ACCESS (cnffile, R_OK)) || (!S_ISREG (st.st_mode)))
302 if (configured == GNUNET_YES)
303 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
304 _("Could not access file `%s': %s\n"), cnffile,
306 GNUNET_free (cnffile);
314 * Close database connection and all prepared statements (we got a DB
317 * @param plugin plugin context
320 iclose (struct Plugin *plugin)
322 struct GNUNET_MysqlStatementHandle *s;
324 for (s = plugin->shead; s != NULL; s = s->next)
328 mysql_stmt_close (s->statement);
329 s->valid = GNUNET_NO;
332 if (plugin->dbf != NULL)
334 mysql_close (plugin->dbf);
342 * Open the connection with the database (and initialize
343 * our default options).
345 * @param plugin plugin context
346 * @return GNUNET_OK on success
349 iopen (struct Plugin *plugin)
354 char *mysql_password;
355 unsigned long long mysql_port;
357 unsigned int timeout;
359 plugin->dbf = mysql_init (NULL);
360 if (plugin->dbf == NULL)
361 return GNUNET_SYSERR;
362 if (plugin->cnffile != NULL)
363 mysql_options (plugin->dbf, MYSQL_READ_DEFAULT_FILE, plugin->cnffile);
364 mysql_options (plugin->dbf, MYSQL_READ_DEFAULT_GROUP, "client");
366 mysql_options (plugin->dbf, MYSQL_OPT_RECONNECT, &reconnect);
367 timeout = 120; /* in seconds */
368 mysql_options (plugin->dbf,
369 MYSQL_OPT_CONNECT_TIMEOUT, (const void *) &timeout);
370 mysql_options(plugin->dbf, MYSQL_SET_CHARSET_NAME, "UTF8");
371 timeout = 60; /* in seconds */
372 mysql_options (plugin->dbf, MYSQL_OPT_READ_TIMEOUT, (const void *) &timeout);
373 mysql_options (plugin->dbf, MYSQL_OPT_WRITE_TIMEOUT, (const void *) &timeout);
375 if (GNUNET_YES == GNUNET_CONFIGURATION_have_value (plugin->env->cfg,
376 "datastore-mysql", "DATABASE"))
377 GNUNET_assert (GNUNET_OK ==
378 GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
379 "datastore-mysql", "DATABASE",
382 mysql_dbname = GNUNET_strdup ("gnunet");
384 if (GNUNET_YES == GNUNET_CONFIGURATION_have_value (plugin->env->cfg,
385 "datastore-mysql", "USER"))
387 GNUNET_assert (GNUNET_OK ==
388 GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
389 "datastore-mysql", "USER",
392 mysql_password = NULL;
393 if (GNUNET_YES == GNUNET_CONFIGURATION_have_value (plugin->env->cfg,
394 "datastore-mysql", "PASSWORD"))
396 GNUNET_assert (GNUNET_OK ==
397 GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
398 "datastore-mysql", "PASSWORD",
402 if (GNUNET_YES == GNUNET_CONFIGURATION_have_value (plugin->env->cfg,
403 "datastore-mysql", "HOST"))
405 GNUNET_assert (GNUNET_OK ==
406 GNUNET_CONFIGURATION_get_value_string (plugin->env->cfg,
407 "datastore-mysql", "HOST",
411 if (GNUNET_YES == GNUNET_CONFIGURATION_have_value (plugin->env->cfg,
412 "datastore-mysql", "PORT"))
414 GNUNET_assert (GNUNET_OK ==
415 GNUNET_CONFIGURATION_get_value_number (plugin->env->cfg, "datastore-mysql",
416 "PORT", &mysql_port));
419 GNUNET_assert (mysql_dbname != NULL);
420 mysql_real_connect (plugin->dbf,
422 mysql_user, mysql_password,
424 (unsigned int) mysql_port, NULL,
425 CLIENT_IGNORE_SIGPIPE);
426 GNUNET_free_non_null (mysql_server);
427 GNUNET_free_non_null (mysql_user);
428 GNUNET_free_non_null (mysql_password);
429 GNUNET_free (mysql_dbname);
430 if (mysql_error (plugin->dbf)[0])
432 LOG_MYSQL (GNUNET_ERROR_TYPE_ERROR,
433 "mysql_real_connect", plugin);
434 return GNUNET_SYSERR;
441 * Run the given MySQL statement.
443 * @param plugin plugin context
444 * @param statement SQL statement to run
445 * @return GNUNET_OK on success, GNUNET_SYSERR on error
448 run_statement (struct Plugin *plugin,
449 const char *statement)
451 if ((NULL == plugin->dbf) && (GNUNET_OK != iopen (plugin)))
452 return GNUNET_SYSERR;
453 mysql_query (plugin->dbf, statement);
454 if (mysql_error (plugin->dbf)[0])
456 LOG_MYSQL (GNUNET_ERROR_TYPE_ERROR,
457 "mysql_query", plugin);
459 return GNUNET_SYSERR;
466 * Create a prepared statement.
468 * @param plugin plugin context
469 * @param statement SQL statement text to prepare
470 * @return NULL on error
472 static struct GNUNET_MysqlStatementHandle *
473 prepared_statement_create (struct Plugin *plugin,
474 const char *statement)
476 struct GNUNET_MysqlStatementHandle *ret;
478 ret = GNUNET_malloc (sizeof (struct GNUNET_MysqlStatementHandle));
479 ret->query = GNUNET_strdup (statement);
480 GNUNET_CONTAINER_DLL_insert (plugin->shead,
488 * Prepare a statement for running.
490 * @param plugin plugin context
491 * @param ret handle to prepared statement
492 * @return GNUNET_OK on success
495 prepare_statement (struct Plugin *plugin,
496 struct GNUNET_MysqlStatementHandle *ret)
498 if (GNUNET_YES == ret->valid)
500 if ((NULL == plugin->dbf) &&
501 (GNUNET_OK != iopen (plugin)))
502 return GNUNET_SYSERR;
503 ret->statement = mysql_stmt_init (plugin->dbf);
504 if (ret->statement == NULL)
507 return GNUNET_SYSERR;
509 if (mysql_stmt_prepare (ret->statement,
511 strlen (ret->query)))
513 GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR,
515 _("Failed to prepare statement `%s'\n"),
517 LOG_MYSQL (GNUNET_ERROR_TYPE_ERROR,
518 "mysql_stmt_prepare",
520 mysql_stmt_close (ret->statement);
521 ret->statement = NULL;
523 return GNUNET_SYSERR;
525 ret->valid = GNUNET_YES;
532 * Bind the parameters for the given MySQL statement
535 * @param plugin plugin context
536 * @param s statement to bind and run
537 * @param ap arguments for the binding
538 * @return GNUNET_SYSERR on error, GNUNET_OK on success
541 init_params (struct Plugin *plugin,
542 struct GNUNET_MysqlStatementHandle *s,
545 MYSQL_BIND qbind[MAX_PARAM];
548 enum enum_field_types ft;
550 pc = mysql_stmt_param_count (s->statement);
553 /* increase internal constant! */
555 return GNUNET_SYSERR;
557 memset (qbind, 0, sizeof (qbind));
560 while ((pc > 0) && (-1 != (int) (ft = va_arg (ap, enum enum_field_types))))
562 qbind[off].buffer_type = ft;
565 case MYSQL_TYPE_FLOAT:
566 qbind[off].buffer = va_arg (ap, float *);
568 case MYSQL_TYPE_LONGLONG:
569 qbind[off].buffer = va_arg (ap, unsigned long long *);
570 qbind[off].is_unsigned = va_arg (ap, int);
572 case MYSQL_TYPE_LONG:
573 qbind[off].buffer = va_arg (ap, unsigned int *);
574 qbind[off].is_unsigned = va_arg (ap, int);
576 case MYSQL_TYPE_VAR_STRING:
577 case MYSQL_TYPE_STRING:
578 case MYSQL_TYPE_BLOB:
579 qbind[off].buffer = va_arg (ap, void *);
580 qbind[off].buffer_length = va_arg (ap, unsigned long);
581 qbind[off].length = va_arg (ap, unsigned long *);
584 /* unsupported type */
586 return GNUNET_SYSERR;
591 if (! ( (pc == 0) && (-1 != (int) ft) && (va_arg (ap, int) == -1) ) )
594 return GNUNET_SYSERR;
596 if (mysql_stmt_bind_param (s->statement, qbind))
598 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
599 _("`%s' failed at %s:%d with error: %s\n"),
600 "mysql_stmt_bind_param",
601 __FILE__, __LINE__, mysql_stmt_error (s->statement));
603 return GNUNET_SYSERR;
605 if (mysql_stmt_execute (s->statement))
607 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
608 _("`%s' for `%s' failed at %s:%d with error: %s\n"),
609 "mysql_stmt_execute",
611 __FILE__, __LINE__, mysql_stmt_error (s->statement));
613 return GNUNET_SYSERR;
620 * Run a prepared SELECT statement.
622 * @param plugin plugin context
623 * @param s statement to run
624 * @param result_size number of elements in results array
625 * @param results pointer to already initialized MYSQL_BIND
626 * array (of sufficient size) for passing results
627 * @param ap pairs and triplets of "MYSQL_TYPE_XXX" keys and their respective
628 * values (size + buffer-reference for pointers); terminated
630 * @return GNUNET_SYSERR on error, otherwise GNUNET_OK or GNUNET_NO (no result)
633 prepared_statement_run_select_va (struct Plugin *plugin,
634 struct GNUNET_MysqlStatementHandle *s,
635 unsigned int result_size,
642 if (GNUNET_OK != prepare_statement (plugin, s))
645 return GNUNET_SYSERR;
647 if (GNUNET_OK != init_params (plugin, s, ap))
650 return GNUNET_SYSERR;
652 rsize = mysql_stmt_field_count (s->statement);
653 if (rsize > result_size)
656 return GNUNET_SYSERR;
658 if (mysql_stmt_bind_result (s->statement, results))
660 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
661 _("`%s' failed at %s:%d with error: %s\n"),
662 "mysql_stmt_bind_result",
663 __FILE__, __LINE__, mysql_stmt_error (s->statement));
665 return GNUNET_SYSERR;
667 ret = mysql_stmt_fetch (s->statement);
668 if (ret == MYSQL_NO_DATA)
672 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
673 _("`%s' failed at %s:%d with error: %s\n"),
675 __FILE__, __LINE__, mysql_stmt_error (s->statement));
677 return GNUNET_SYSERR;
679 mysql_stmt_reset (s->statement);
685 * Run a prepared SELECT statement.
687 * @param plugin plugin context
688 * @param s statement to run
689 * @param result_size number of elements in results array
690 * @param results pointer to already initialized MYSQL_BIND
691 * array (of sufficient size) for passing results
692 * @param ... pairs and triplets of "MYSQL_TYPE_XXX" keys and their respective
693 * values (size + buffer-reference for pointers); terminated
695 * @return GNUNET_SYSERR on error, otherwise
696 * the number of successfully affected (or queried) rows
699 prepared_statement_run_select (struct Plugin *plugin,
700 struct GNUNET_MysqlStatementHandle *s,
701 unsigned int result_size,
708 va_start (ap, results);
709 ret = prepared_statement_run_select_va (plugin, s,
710 result_size, results,
718 * Run a prepared statement that does NOT produce results.
720 * @param plugin plugin context
721 * @param s statement to run
722 * @param insert_id NULL or address where to store the row ID of whatever
723 * was inserted (only for INSERT statements!)
724 * @param ... pairs and triplets of "MYSQL_TYPE_XXX" keys and their respective
725 * values (size + buffer-reference for pointers); terminated
727 * @return GNUNET_SYSERR on error, otherwise
728 * the number of successfully affected rows
731 prepared_statement_run (struct Plugin *plugin,
732 struct GNUNET_MysqlStatementHandle *s,
733 unsigned long long *insert_id, ...)
738 if (GNUNET_OK != prepare_statement (plugin, s))
739 return GNUNET_SYSERR;
740 va_start (ap, insert_id);
741 if (GNUNET_OK != init_params (plugin, s, ap))
744 return GNUNET_SYSERR;
747 affected = mysql_stmt_affected_rows (s->statement);
748 if (NULL != insert_id)
749 *insert_id = (unsigned long long) mysql_stmt_insert_id (s->statement);
750 mysql_stmt_reset (s->statement);
756 * Delete an entry from the gn090 table.
758 * @param plugin plugin context
759 * @param uid unique ID of the entry to delete
760 * @return GNUNET_OK on success, GNUNET_NO if no such value exists, GNUNET_SYSERR on error
763 do_delete_entry (struct Plugin *plugin,
764 unsigned long long uid)
769 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
770 "Deleting value %llu from gn090 table\n",
773 ret = prepared_statement_run (plugin,
774 plugin->delete_entry_by_uid,
776 MYSQL_TYPE_LONGLONG, &uid, GNUNET_YES,
780 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
781 "Deleting value %llu from gn090 table failed\n",
788 * Get an estimate of how much space the database is
791 * @param cls our "struct Plugin *"
792 * @return number of bytes used on disk
794 static unsigned long long
795 mysql_plugin_estimate_size (void *cls)
797 struct Plugin *plugin = cls;
801 memset (cbind, 0, sizeof (cbind));
803 cbind[0].buffer_type = MYSQL_TYPE_LONGLONG;
804 cbind[0].buffer = &total;
805 cbind[0].is_unsigned = GNUNET_NO;
807 prepared_statement_run_select (plugin,
817 * Store an item in the datastore.
820 * @param key key for the item
821 * @param size number of bytes in data
822 * @param data content stored
823 * @param type type of the content
824 * @param priority priority of the content
825 * @param anonymity anonymity-level for the content
826 * @param replication replication-level for the content
827 * @param expiration expiration time for the content
828 * @param msg set to error message
829 * @return GNUNET_OK on success
832 mysql_plugin_put (void *cls,
833 const GNUNET_HashCode * key,
836 enum GNUNET_BLOCK_Type type,
839 uint32_t replication,
840 struct GNUNET_TIME_Absolute expiration,
843 struct Plugin *plugin = cls;
844 unsigned int irepl = replication;
845 unsigned int ipriority = priority;
846 unsigned int ianonymity = anonymity;
847 unsigned long long lexpiration = expiration.abs_value;
848 unsigned long hashSize;
849 unsigned long hashSize2;
851 unsigned long rvalue;
852 GNUNET_HashCode vhash;
854 if (size > MAX_DATUM_SIZE)
857 return GNUNET_SYSERR;
859 hashSize = sizeof (GNUNET_HashCode);
860 hashSize2 = sizeof (GNUNET_HashCode);
862 GNUNET_CRYPTO_hash (data, size, &vhash);
863 rvalue = (unsigned long) GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX);
865 prepared_statement_run (plugin,
866 plugin->insert_entry,
868 MYSQL_TYPE_LONG, &irepl, GNUNET_YES,
869 MYSQL_TYPE_LONG, &type, GNUNET_YES,
870 MYSQL_TYPE_LONG, &ipriority, GNUNET_YES,
871 MYSQL_TYPE_LONG, &ianonymity, GNUNET_YES,
872 MYSQL_TYPE_LONGLONG, &lexpiration, GNUNET_YES,
873 MYSQL_TYPE_LONGLONG, &rvalue, GNUNET_YES,
874 MYSQL_TYPE_BLOB, key, hashSize, &hashSize,
875 MYSQL_TYPE_BLOB, &vhash, hashSize2, &hashSize2,
876 MYSQL_TYPE_BLOB, data, lsize, &lsize,
878 return GNUNET_SYSERR;
880 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
881 "Inserted value `%s' with size %u into gn090 table\n",
883 (unsigned int) size);
886 plugin->env->duc (plugin->env->cls,
893 * Update the priority for a particular key in the datastore. If
894 * the expiration time in value is different than the time found in
895 * the datastore, the higher value should be kept. For the
896 * anonymity level, the lower value is to be used. The specified
897 * priority should be added to the existing priority, ignoring the
900 * Note that it is possible for multiple values to match this put.
901 * In that case, all of the respective values are updated.
903 * @param cls our "struct Plugin*"
904 * @param uid unique identifier of the datum
905 * @param delta by how much should the priority
906 * change? If priority + delta < 0 the
907 * priority should be set to 0 (never go
909 * @param expire new expiration time should be the
910 * MAX of any existing expiration time and
912 * @param msg set to error message
913 * @return GNUNET_OK on success
916 mysql_plugin_update (void *cls,
919 struct GNUNET_TIME_Absolute expire,
922 struct Plugin *plugin = cls;
923 unsigned long long vkey = uid;
924 unsigned long long lexpire = expire.abs_value;
928 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
929 "Updating value %llu adding %d to priority and maxing exp at %llu\n",
934 ret = prepared_statement_run (plugin,
935 plugin->update_entry,
937 MYSQL_TYPE_LONG, &delta, GNUNET_NO,
938 MYSQL_TYPE_LONGLONG, &lexpire, GNUNET_YES,
939 MYSQL_TYPE_LONGLONG, &lexpire, GNUNET_YES,
940 MYSQL_TYPE_LONGLONG, &vkey, GNUNET_YES,
942 if (ret != GNUNET_OK)
944 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
945 "Failed to update value %llu\n",
953 * Run the given select statement and call 'proc' on the resulting
954 * values (which must be in particular positions).
956 * @param plugin the plugin handle
957 * @param stmt select statement to run
958 * @param proc function to call on result
959 * @param proc_cls closure for proc
960 * @param ... arguments to initialize stmt
963 execute_select (struct Plugin *plugin,
964 struct GNUNET_MysqlStatementHandle *stmt,
965 PluginDatumProcessor proc, void *proc_cls,
971 unsigned int priority;
972 unsigned int anonymity;
973 unsigned long long exp;
974 unsigned long hashSize;
976 unsigned long long uid;
977 char value[GNUNET_DATASTORE_MAX_VALUE_SIZE];
979 struct GNUNET_TIME_Absolute expiration;
982 hashSize = sizeof (GNUNET_HashCode);
983 memset (rbind, 0, sizeof (rbind));
984 rbind[0].buffer_type = MYSQL_TYPE_LONG;
985 rbind[0].buffer = &type;
986 rbind[0].is_unsigned = 1;
987 rbind[1].buffer_type = MYSQL_TYPE_LONG;
988 rbind[1].buffer = &priority;
989 rbind[1].is_unsigned = 1;
990 rbind[2].buffer_type = MYSQL_TYPE_LONG;
991 rbind[2].buffer = &anonymity;
992 rbind[2].is_unsigned = 1;
993 rbind[3].buffer_type = MYSQL_TYPE_LONGLONG;
994 rbind[3].buffer = &exp;
995 rbind[3].is_unsigned = 1;
996 rbind[4].buffer_type = MYSQL_TYPE_BLOB;
997 rbind[4].buffer = &key;
998 rbind[4].buffer_length = hashSize;
999 rbind[4].length = &hashSize;
1000 rbind[5].buffer_type = MYSQL_TYPE_BLOB;
1001 rbind[5].buffer = value;
1002 rbind[5].buffer_length = size = sizeof (value);
1003 rbind[5].length = &size;
1004 rbind[6].buffer_type = MYSQL_TYPE_LONGLONG;
1005 rbind[6].buffer = &uid;
1006 rbind[6].is_unsigned = 1;
1008 va_start (ap, proc_cls);
1009 ret = prepared_statement_run_select_va (plugin,
1017 NULL, 0, NULL, 0, 0, 0,
1018 GNUNET_TIME_UNIT_ZERO_ABS, 0);
1021 GNUNET_assert (size <= sizeof(value));
1022 if ( (rbind[4].buffer_length != sizeof (GNUNET_HashCode)) ||
1023 (hashSize != sizeof (GNUNET_HashCode)) )
1027 NULL, 0, NULL, 0, 0, 0,
1028 GNUNET_TIME_UNIT_ZERO_ABS, 0);
1032 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1033 "Found %u-byte value under key `%s' with prio %u, anon %u, expire %llu selecting from gn090 table\n",
1034 (unsigned int) size,
1040 GNUNET_assert (size < MAX_DATUM_SIZE);
1041 expiration.abs_value = exp;
1042 ret = proc (proc_cls,
1045 type, priority, anonymity, expiration,
1047 if (ret == GNUNET_NO)
1049 do_delete_entry (plugin, uid);
1051 plugin->env->duc (plugin->env->cls,
1059 * Get one of the results for a particular key in the datastore.
1061 * @param cls closure
1062 * @param offset offset of the result (modulo num-results);
1063 * specific ordering does not matter for the offset
1064 * @param key key to match, never NULL
1065 * @param vhash hash of the value, maybe NULL (to
1066 * match all values that have the right key).
1067 * Note that for DBlocks there is no difference
1068 * betwen key and vhash, but for other blocks
1070 * @param type entries of which type are relevant?
1071 * Use 0 for any type.
1072 * @param proc function to call on the matching value,
1073 * with NULL for if no value matches
1074 * @param proc_cls closure for proc
1077 mysql_plugin_get_key (void *cls,
1079 const GNUNET_HashCode *key,
1080 const GNUNET_HashCode *vhash,
1081 enum GNUNET_BLOCK_Type type,
1082 PluginDatumProcessor proc, void *proc_cls)
1084 struct Plugin *plugin = cls;
1086 MYSQL_BIND cbind[1];
1088 unsigned long hashSize;
1089 unsigned long hashSize2;
1090 unsigned long long off;
1092 GNUNET_assert (key != NULL);
1093 GNUNET_assert (NULL != proc);
1094 hashSize = sizeof (GNUNET_HashCode);
1095 hashSize2 = sizeof (GNUNET_HashCode);
1096 memset (cbind, 0, sizeof (cbind));
1098 cbind[0].buffer_type = MYSQL_TYPE_LONGLONG;
1099 cbind[0].buffer = &total;
1100 cbind[0].is_unsigned = GNUNET_NO;
1106 prepared_statement_run_select (plugin,
1107 plugin->count_entry_by_hash_vhash_and_type,
1109 MYSQL_TYPE_BLOB, key, hashSize, &hashSize,
1110 MYSQL_TYPE_BLOB, vhash, hashSize2, &hashSize2,
1111 MYSQL_TYPE_LONG, &type, GNUNET_YES,
1117 prepared_statement_run_select (plugin,
1118 plugin->count_entry_by_hash_and_type,
1120 MYSQL_TYPE_BLOB, key, hashSize, &hashSize,
1121 MYSQL_TYPE_LONG, &type, GNUNET_YES,
1130 prepared_statement_run_select (plugin,
1131 plugin->count_entry_by_hash_and_vhash,
1133 MYSQL_TYPE_BLOB, key, hashSize, &hashSize,
1134 MYSQL_TYPE_BLOB, vhash, hashSize2, &hashSize2,
1141 prepared_statement_run_select (plugin,
1142 plugin->count_entry_by_hash,
1144 MYSQL_TYPE_BLOB, key, hashSize, &hashSize,
1148 if ((ret != GNUNET_OK) || (0 >= total))
1151 NULL, 0, NULL, 0, 0, 0,
1152 GNUNET_TIME_UNIT_ZERO_ABS, 0);
1155 offset = offset % total;
1156 off = (unsigned long long) offset;
1158 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1159 "Obtaining %llu/%lld result for GET `%s'\n",
1165 if (type != GNUNET_BLOCK_TYPE_ANY)
1169 execute_select (plugin,
1170 plugin->select_entry_by_hash_vhash_and_type,
1172 MYSQL_TYPE_BLOB, key, hashSize, &hashSize,
1173 MYSQL_TYPE_BLOB, vhash, hashSize, &hashSize,
1174 MYSQL_TYPE_LONG, &type, GNUNET_YES,
1175 MYSQL_TYPE_LONGLONG, &off, GNUNET_YES,
1180 execute_select (plugin,
1181 plugin->select_entry_by_hash_and_type,
1183 MYSQL_TYPE_BLOB, key, hashSize, &hashSize,
1184 MYSQL_TYPE_LONG, &type, GNUNET_YES,
1185 MYSQL_TYPE_LONGLONG, &off, GNUNET_YES,
1193 execute_select (plugin,
1194 plugin->select_entry_by_hash_and_vhash,
1196 MYSQL_TYPE_BLOB, key, hashSize, &hashSize,
1197 MYSQL_TYPE_BLOB, vhash, hashSize, &hashSize,
1198 MYSQL_TYPE_LONGLONG, &off, GNUNET_YES,
1203 execute_select (plugin,
1204 plugin->select_entry_by_hash,
1206 MYSQL_TYPE_BLOB, key, hashSize, &hashSize,
1207 MYSQL_TYPE_LONGLONG, &off, GNUNET_YES,
1215 * Get a zero-anonymity datum from the datastore.
1217 * @param cls our "struct Plugin*"
1218 * @param offset offset of the result
1219 * @param type entries of which type should be considered?
1220 * Use 0 for any type.
1221 * @param proc function to call on a matching value or NULL
1222 * @param proc_cls closure for iter
1225 mysql_plugin_get_zero_anonymity (void *cls,
1227 enum GNUNET_BLOCK_Type type,
1228 PluginDatumProcessor proc, void *proc_cls)
1230 struct Plugin *plugin = cls;
1231 unsigned long long off;
1233 off = (unsigned long long) offset;
1234 execute_select (plugin,
1237 MYSQL_TYPE_LONG, &type, GNUNET_YES,
1238 MYSQL_TYPE_LONGLONG, &off, GNUNET_YES,
1245 * Context for 'repl_proc' function.
1253 struct Plugin *plugin;
1256 * Function to call for the result (or the NULL).
1258 PluginDatumProcessor proc;
1268 * Wrapper for the processor for 'mysql_plugin_get_replication'.
1269 * Decrements the replication counter and calls the original
1272 * @param cls closure
1273 * @param key key for the content
1274 * @param size number of bytes in data
1275 * @param data content stored
1276 * @param type type of the content
1277 * @param priority priority of the content
1278 * @param anonymity anonymity-level for the content
1279 * @param expiration expiration time for the content
1280 * @param uid unique identifier for the datum;
1281 * maybe 0 if no unique identifier is available
1283 * @return GNUNET_SYSERR to abort the iteration, GNUNET_OK to continue
1284 * (continue on call to "next", of course),
1285 * GNUNET_NO to delete the item and continue (if supported)
1288 repl_proc (void *cls,
1289 const GNUNET_HashCode *key,
1292 enum GNUNET_BLOCK_Type type,
1295 struct GNUNET_TIME_Absolute expiration,
1298 struct ReplCtx *rc = cls;
1299 struct Plugin *plugin = rc->plugin;
1300 unsigned long long oid;
1304 ret = rc->proc (rc->proc_cls,
1307 type, priority, anonymity, expiration,
1311 oid = (unsigned long long) uid;
1312 iret = prepared_statement_run (plugin,
1315 MYSQL_TYPE_LONGLONG, &oid, GNUNET_YES,
1317 if (iret == GNUNET_SYSERR)
1319 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1320 "Failed to reduce replication counter\n");
1321 return GNUNET_SYSERR;
1329 * Get a random item for replication. Returns a single, not expired,
1330 * random item from those with the highest replication counters. The
1331 * item's replication counter is decremented by one IF it was positive
1332 * before. Call 'proc' with all values ZERO or NULL if the datastore
1335 * @param cls closure
1336 * @param proc function to call the value (once only).
1337 * @param proc_cls closure for proc
1340 mysql_plugin_get_replication (void *cls,
1341 PluginDatumProcessor proc, void *proc_cls)
1343 struct Plugin *plugin = cls;
1348 rc.proc_cls = proc_cls;
1349 execute_select (plugin,
1350 plugin->select_replication,
1358 * Get a random item for expiration.
1359 * Call 'proc' with all values ZERO or NULL if the datastore is empty.
1361 * @param cls closure
1362 * @param proc function to call the value (once only).
1363 * @param proc_cls closure for proc
1366 mysql_plugin_get_expiration (void *cls,
1367 PluginDatumProcessor proc, void *proc_cls)
1369 struct Plugin *plugin = cls;
1372 nt = (long long) GNUNET_TIME_absolute_get().abs_value;
1373 execute_select (plugin,
1374 plugin->select_expiration,
1376 MYSQL_TYPE_LONGLONG, &nt, GNUNET_YES,
1385 * @param cls the "struct Plugin*"
1388 mysql_plugin_drop (void *cls)
1390 struct Plugin *plugin = cls;
1392 if (GNUNET_OK != run_statement (plugin,
1393 "DROP TABLE gn090"))
1395 plugin->env->duc (plugin->env->cls, 0);
1400 * Entry point for the plugin.
1402 * @param cls the "struct GNUNET_DATASTORE_PluginEnvironment*"
1403 * @return our "struct Plugin*"
1406 libgnunet_plugin_datastore_mysql_init (void *cls)
1408 struct GNUNET_DATASTORE_PluginEnvironment *env = cls;
1409 struct GNUNET_DATASTORE_PluginFunctions *api;
1410 struct Plugin *plugin;
1412 plugin = GNUNET_malloc (sizeof (struct Plugin));
1414 plugin->cnffile = get_my_cnf_path (env->cfg);
1415 if (GNUNET_OK != iopen (plugin))
1418 GNUNET_free_non_null (plugin->cnffile);
1419 GNUNET_free (plugin);
1422 #define MRUNS(a) (GNUNET_OK != run_statement (plugin, a) )
1423 #define PINIT(a,b) (NULL == (a = prepared_statement_create(plugin, b)))
1424 if (MRUNS ("CREATE TABLE IF NOT EXISTS gn090 ("
1425 " repl INT(11) UNSIGNED NOT NULL DEFAULT 0,"
1426 " type INT(11) UNSIGNED NOT NULL DEFAULT 0,"
1427 " prio INT(11) UNSIGNED NOT NULL DEFAULT 0,"
1428 " anonLevel INT(11) UNSIGNED NOT NULL DEFAULT 0,"
1429 " expire BIGINT UNSIGNED NOT NULL DEFAULT 0,"
1430 " rvalue BIGINT UNSIGNED NOT NULL,"
1431 " hash BINARY(64) NOT NULL DEFAULT '',"
1432 " vhash BINARY(64) NOT NULL DEFAULT '',"
1433 " value BLOB NOT NULL DEFAULT '',"
1434 " uid BIGINT NOT NULL AUTO_INCREMENT,"
1435 " PRIMARY KEY (uid),"
1436 " INDEX idx_hash (hash(64)),"
1437 " INDEX idx_hash_uid (hash(64),uid),"
1438 " INDEX idx_hash_vhash (hash(64),vhash(64)),"
1439 " INDEX idx_hash_type_uid (hash(64),type,uid),"
1440 " INDEX idx_prio (prio),"
1441 " INDEX idx_repl_rvalue (repl,rvalue),"
1442 " INDEX idx_expire_prio (expire,prio),"
1443 " INDEX idx_anonLevel_uid (anonLevel,uid)"
1444 ") ENGINE=InnoDB") ||
1445 MRUNS ("SET AUTOCOMMIT = 1") ||
1446 PINIT (plugin->insert_entry, INSERT_ENTRY) ||
1447 PINIT (plugin->delete_entry_by_uid, DELETE_ENTRY_BY_UID) ||
1448 PINIT (plugin->select_entry_by_hash, SELECT_ENTRY_BY_HASH) ||
1449 PINIT (plugin->select_entry_by_hash_and_vhash, SELECT_ENTRY_BY_HASH_AND_VHASH)
1450 || PINIT (plugin->select_entry_by_hash_and_type, SELECT_ENTRY_BY_HASH_AND_TYPE)
1451 || PINIT (plugin->select_entry_by_hash_vhash_and_type,
1452 SELECT_ENTRY_BY_HASH_VHASH_AND_TYPE)
1453 || PINIT (plugin->count_entry_by_hash, COUNT_ENTRY_BY_HASH)
1454 || PINIT (plugin->get_size, SELECT_SIZE)
1455 || PINIT (plugin->count_entry_by_hash_and_vhash, COUNT_ENTRY_BY_HASH_AND_VHASH)
1456 || PINIT (plugin->count_entry_by_hash_and_type, COUNT_ENTRY_BY_HASH_AND_TYPE)
1457 || PINIT (plugin->count_entry_by_hash_vhash_and_type,
1458 COUNT_ENTRY_BY_HASH_VHASH_AND_TYPE)
1459 || PINIT (plugin->update_entry, UPDATE_ENTRY)
1460 || PINIT (plugin->dec_repl, DEC_REPL)
1461 || PINIT (plugin->zero_iter, SELECT_IT_NON_ANONYMOUS)
1462 || PINIT (plugin->select_expiration, SELECT_IT_EXPIRATION)
1463 || PINIT (plugin->select_replication, SELECT_IT_REPLICATION) )
1466 GNUNET_free_non_null (plugin->cnffile);
1467 GNUNET_free (plugin);
1473 api = GNUNET_malloc (sizeof (struct GNUNET_DATASTORE_PluginFunctions));
1475 api->estimate_size = &mysql_plugin_estimate_size;
1476 api->put = &mysql_plugin_put;
1477 api->update = &mysql_plugin_update;
1478 api->get_key = &mysql_plugin_get_key;
1479 api->get_replication = &mysql_plugin_get_replication;
1480 api->get_expiration = &mysql_plugin_get_expiration;
1481 api->get_zero_anonymity = &mysql_plugin_get_zero_anonymity;
1482 api->drop = &mysql_plugin_drop;
1483 GNUNET_log_from (GNUNET_ERROR_TYPE_INFO,
1484 "mysql", _("Mysql database running\n"));
1490 * Exit point from the plugin.
1491 * @param cls our "struct Plugin*"
1492 * @return always NULL
1495 libgnunet_plugin_datastore_mysql_done (void *cls)
1497 struct GNUNET_DATASTORE_PluginFunctions *api = cls;
1498 struct Plugin *plugin = api->cls;
1499 struct GNUNET_MysqlStatementHandle *s;
1502 while (NULL != (s = plugin->shead))
1504 GNUNET_CONTAINER_DLL_remove (plugin->shead,
1507 GNUNET_free (s->query);
1510 GNUNET_free_non_null (plugin->cnffile);
1511 GNUNET_free (plugin);
1513 mysql_library_end ();
1517 /* end of plugin_datastore_mysql.c */