2 This file is part of GNUnet
3 (C) 2004, 2005, 2006, 2007, 2009 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 2, 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/gnunet-service-datastore.c
23 * @brief Management for the datastore for files stored on a GNUnet node
24 * @author Christian Grothoff
28 #include "gnunet_util_lib.h"
29 #include "gnunet_protocols.h"
30 #include "gnunet_statistics_service.h"
31 #include "gnunet_datastore_plugin.h"
32 #include "datastore.h"
35 * How many messages do we queue at most per client?
37 #define MAX_PENDING 1024
40 * How long are we at most keeping "expired" content
41 * past the expiration date in the database?
43 #define MAX_EXPIRE_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15)
46 * How fast are we allowed to query the database for deleting
47 * expired content? (1 item per second).
49 #define MIN_EXPIRE_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
52 * Name under which we store current space consumption.
54 static char *quota_stat_name;
57 * After how many payload-changing operations
58 * do we sync our statistics?
60 #define MAX_STAT_SYNC_LAG 50
64 * Our datastore plugin.
66 struct DatastorePlugin
70 * API of the transport as returned by the plugin's
71 * initialization function.
73 struct GNUNET_DATASTORE_PluginFunctions *api;
76 * Short name for the plugin (i.e. "sqlite").
81 * Name of the library (i.e. "gnunet_plugin_datastore_sqlite").
86 * Environment this transport service is using
89 struct GNUNET_DATASTORE_PluginEnvironment env;
95 * Linked list of active reservations.
97 struct ReservationList
101 * This is a linked list.
103 struct ReservationList *next;
106 * Client that made the reservation.
108 struct GNUNET_SERVER_Client *client;
111 * Number of bytes (still) reserved.
116 * Number of items (still) reserved.
121 * Reservation identifier.
130 * Our datastore plugin (NULL if not available).
132 static struct DatastorePlugin *plugin;
135 * Linked list of space reservations made by clients.
137 static struct ReservationList *reservations;
140 * Bloomfilter to quickly tell if we don't have the content.
142 static struct GNUNET_CONTAINER_BloomFilter *filter;
145 * How much space are we allowed to use?
147 static unsigned long long quota;
150 * Should the database be dropped on exit?
155 * Name of our plugin.
157 static char *plugin_name;
160 * How much space are we using for the cache? (space available for
161 * insertions that will be instantly reclaimed by discarding less
162 * important content --- or possibly whatever we just inserted into
165 static unsigned long long cache_size;
168 * How much space have we currently reserved?
170 static unsigned long long reserved;
173 * How much data are we currently storing
176 static unsigned long long payload;
179 * Number of updates that were made to the
180 * payload value since we last synchronized
181 * it with the statistics service.
183 static unsigned int lastSync;
186 * Did we get an answer from statistics?
188 static int stats_worked;
191 * Identity of the task that is used to delete
194 static GNUNET_SCHEDULER_TaskIdentifier expired_kill_task;
199 const struct GNUNET_CONFIGURATION_Handle *cfg;
202 * Minimum time that content should have to not be discarded instantly
203 * (time stamp of any content that we've been discarding recently to
204 * stay below the quota). FOREVER if we had to expire content with
207 static struct GNUNET_TIME_Absolute min_expiration;
210 * Handle for reporting statistics.
212 static struct GNUNET_STATISTICS_Handle *stats;
216 * Synchronize our utilization statistics with the
217 * statistics service.
222 GNUNET_STATISTICS_set (stats, quota_stat_name, payload, GNUNET_YES);
223 GNUNET_STATISTICS_set (stats, "# utilization by current datastore", payload, GNUNET_NO);
230 * Context for transmitting replies to clients.
232 struct TransmitCallbackContext
236 * We keep these in a doubly-linked list (for cleanup).
238 struct TransmitCallbackContext *next;
241 * We keep these in a doubly-linked list (for cleanup).
243 struct TransmitCallbackContext *prev;
246 * The message that we're asked to transmit.
248 struct GNUNET_MessageHeader *msg;
251 * Handle for the transmission request.
253 struct GNUNET_SERVER_TransmitHandle *th;
256 * Client that we are transmitting to.
258 struct GNUNET_SERVER_Client *client;
264 * Head of the doubly-linked list (for cleanup).
266 static struct TransmitCallbackContext *tcc_head;
269 * Tail of the doubly-linked list (for cleanup).
271 static struct TransmitCallbackContext *tcc_tail;
274 * Have we already cleaned up the TCCs and are hence no longer
275 * willing (or able) to transmit anything to anyone?
277 static int cleaning_done;
280 * Handle for pending get request.
282 static struct GNUNET_STATISTICS_GetHandle *stat_get;
286 * Task that is used to remove expired entries from
287 * the datastore. This task will schedule itself
288 * again automatically to always delete all expired
291 * @param cls not used
292 * @param tc task context
295 delete_expired (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
299 * Iterate over the expired items stored in the datastore.
300 * Delete all expired items; once we have processed all
301 * expired items, re-schedule the "delete_expired" task.
303 * @param cls not used
304 * @param key key for the content
305 * @param size number of bytes in data
306 * @param data content stored
307 * @param type type of the content
308 * @param priority priority of the content
309 * @param anonymity anonymity-level for the content
310 * @param expiration expiration time for the content
311 * @param uid unique identifier for the datum;
312 * maybe 0 if no unique identifier is available
314 * @return GNUNET_SYSERR to abort the iteration, GNUNET_OK to continue
315 * (continue on call to "next", of course),
316 * GNUNET_NO to delete the item and continue (if supported)
319 expired_processor (void *cls, const struct GNUNET_HashCode * key, uint32_t size,
320 const void *data, enum GNUNET_BLOCK_Type type,
321 uint32_t priority, uint32_t anonymity,
322 struct GNUNET_TIME_Absolute expiration, uint64_t uid)
324 struct GNUNET_TIME_Absolute now;
329 GNUNET_SCHEDULER_add_delayed_with_priority (MAX_EXPIRE_DELAY,
330 GNUNET_SCHEDULER_PRIORITY_IDLE,
331 &delete_expired, NULL);
332 return GNUNET_SYSERR;
334 now = GNUNET_TIME_absolute_get ();
335 if (expiration.abs_value > now.abs_value)
337 /* finished processing */
339 GNUNET_SCHEDULER_add_delayed_with_priority (MAX_EXPIRE_DELAY,
340 GNUNET_SCHEDULER_PRIORITY_IDLE,
341 &delete_expired, NULL);
342 return GNUNET_SYSERR;
344 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
345 "Deleting content `%s' of type %u that expired %llu ms ago\n",
346 GNUNET_h2s (key), type,
347 (unsigned long long) (now.abs_value - expiration.abs_value));
348 min_expiration = now;
349 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes expired"), size,
351 GNUNET_CONTAINER_bloomfilter_remove (filter, key);
353 GNUNET_SCHEDULER_add_delayed_with_priority (MIN_EXPIRE_DELAY,
354 GNUNET_SCHEDULER_PRIORITY_IDLE,
355 &delete_expired, NULL);
361 * Task that is used to remove expired entries from
362 * the datastore. This task will schedule itself
363 * again automatically to always delete all expired
366 * @param cls not used
367 * @param tc task context
370 delete_expired (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
372 expired_kill_task = GNUNET_SCHEDULER_NO_TASK;
373 plugin->api->get_expiration (plugin->api->cls, &expired_processor, NULL);
378 * An iterator over a set of items stored in the datastore
379 * that deletes until we're happy with respect to our quota.
382 * @param key key for the content
383 * @param size number of bytes in data
384 * @param data content stored
385 * @param type type of the content
386 * @param priority priority of the content
387 * @param anonymity anonymity-level for the content
388 * @param expiration expiration time for the content
389 * @param uid unique identifier for the datum;
390 * maybe 0 if no unique identifier is available
392 * @return GNUNET_SYSERR to abort the iteration, GNUNET_OK to continue
393 * (continue on call to "next", of course),
394 * GNUNET_NO to delete the item and continue (if supported)
397 quota_processor (void *cls, const struct GNUNET_HashCode * key, uint32_t size,
398 const void *data, enum GNUNET_BLOCK_Type type,
399 uint32_t priority, uint32_t anonymity,
400 struct GNUNET_TIME_Absolute expiration, uint64_t uid)
402 unsigned long long *need = cls;
405 return GNUNET_SYSERR;
406 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
407 "Deleting %llu bytes of low-priority (%u) content `%s' of type %u at %llu ms prior to expiration (still trying to free another %llu bytes)\n",
408 (unsigned long long) (size + GNUNET_DATASTORE_ENTRY_OVERHEAD),
409 (unsigned int) priority,
410 GNUNET_h2s (key), type,
411 (unsigned long long) GNUNET_TIME_absolute_get_remaining (expiration).rel_value,
413 if (size + GNUNET_DATASTORE_ENTRY_OVERHEAD > *need)
416 *need -= size + GNUNET_DATASTORE_ENTRY_OVERHEAD;
418 min_expiration = GNUNET_TIME_UNIT_FOREVER_ABS;
420 min_expiration = expiration;
421 GNUNET_STATISTICS_update (stats,
422 gettext_noop ("# bytes purged (low-priority)"),
424 GNUNET_CONTAINER_bloomfilter_remove (filter, key);
430 * Manage available disk space by running tasks
431 * that will discard content if necessary. This
432 * function will be run whenever a request for
433 * "need" bytes of storage could only be satisfied
434 * by eating into the "cache" (and we want our cache
437 * @param need number of bytes of content that were
438 * placed into the "cache" (and hence the
439 * number of bytes that should be removed).
442 manage_space (unsigned long long need)
444 unsigned long long last;
446 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
447 "Asked to free up %llu bytes of cache space\n", need);
449 while ((need > 0) && (last != need))
452 plugin->api->get_expiration (plugin->api->cls, "a_processor, &need);
458 * Function called to notify a client about the socket
459 * begin ready to queue more data. "buf" will be
460 * NULL and "size" zero if the socket was closed for
461 * writing in the meantime.
464 * @param size number of bytes available in buf
465 * @param buf where the callee should write the message
466 * @return number of bytes written to buf
469 transmit_callback (void *cls, size_t size, void *buf)
471 struct TransmitCallbackContext *tcc = cls;
475 GNUNET_CONTAINER_DLL_remove (tcc_head, tcc_tail, tcc);
476 msize = ntohs (tcc->msg->size);
479 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
480 _("Transmission to client failed!\n"));
481 GNUNET_SERVER_receive_done (tcc->client, GNUNET_SYSERR);
482 GNUNET_SERVER_client_drop (tcc->client);
483 GNUNET_free (tcc->msg);
487 GNUNET_assert (size >= msize);
488 memcpy (buf, tcc->msg, msize);
489 GNUNET_SERVER_receive_done (tcc->client, GNUNET_OK);
490 GNUNET_SERVER_client_drop (tcc->client);
491 GNUNET_free (tcc->msg);
498 * Transmit the given message to the client.
500 * @param client target of the message
501 * @param msg message to transmit, will be freed!
504 transmit (struct GNUNET_SERVER_Client *client, struct GNUNET_MessageHeader *msg)
506 struct TransmitCallbackContext *tcc;
508 if (GNUNET_YES == cleaning_done)
510 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
511 _("Shutdown in progress, aborting transmission.\n"));
512 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
516 tcc = GNUNET_malloc (sizeof (struct TransmitCallbackContext));
518 tcc->client = client;
521 GNUNET_SERVER_notify_transmit_ready (client, ntohs (msg->size),
522 GNUNET_TIME_UNIT_FOREVER_REL,
523 &transmit_callback, tcc)))
526 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
531 GNUNET_SERVER_client_keep (client);
532 GNUNET_CONTAINER_DLL_insert (tcc_head, tcc_tail, tcc);
537 * Transmit a status code to the client.
539 * @param client receiver of the response
540 * @param code status code
541 * @param msg optional error message (can be NULL)
544 transmit_status (struct GNUNET_SERVER_Client *client, int code, const char *msg)
546 struct StatusMessage *sm;
549 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
550 "Transmitting `%s' message with value %d and message `%s'\n",
551 "STATUS", code, msg != NULL ? msg : "(none)");
552 slen = (msg == NULL) ? 0 : strlen (msg) + 1;
553 sm = GNUNET_malloc (sizeof (struct StatusMessage) + slen);
554 sm->header.size = htons (sizeof (struct StatusMessage) + slen);
555 sm->header.type = htons (GNUNET_MESSAGE_TYPE_DATASTORE_STATUS);
556 sm->status = htonl (code);
557 sm->min_expiration = GNUNET_TIME_absolute_hton (min_expiration);
559 memcpy (&sm[1], msg, slen);
560 transmit (client, &sm->header);
566 * Function that will transmit the given datastore entry
569 * @param cls closure, pointer to the client (of type GNUNET_SERVER_Client).
570 * @param key key for the content
571 * @param size number of bytes in data
572 * @param data content stored
573 * @param type type of the content
574 * @param priority priority of the content
575 * @param anonymity anonymity-level for the content
576 * @param expiration expiration time for the content
577 * @param uid unique identifier for the datum;
578 * maybe 0 if no unique identifier is available
580 * @return GNUNET_SYSERR to abort the iteration, GNUNET_OK to continue,
581 * GNUNET_NO to delete the item and continue (if supported)
584 transmit_item (void *cls, const struct GNUNET_HashCode * key, uint32_t size,
585 const void *data, enum GNUNET_BLOCK_Type type, uint32_t priority,
586 uint32_t anonymity, struct GNUNET_TIME_Absolute expiration,
589 struct GNUNET_SERVER_Client *client = cls;
590 struct GNUNET_MessageHeader *end;
591 struct DataMessage *dm;
595 /* transmit 'DATA_END' */
596 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transmitting `%s' message\n",
598 end = GNUNET_malloc (sizeof (struct GNUNET_MessageHeader));
599 end->size = htons (sizeof (struct GNUNET_MessageHeader));
600 end->type = htons (GNUNET_MESSAGE_TYPE_DATASTORE_DATA_END);
601 transmit (client, end);
602 GNUNET_SERVER_client_drop (client);
605 GNUNET_assert (sizeof (struct DataMessage) + size <
606 GNUNET_SERVER_MAX_MESSAGE_SIZE);
607 dm = GNUNET_malloc (sizeof (struct DataMessage) + size);
608 dm->header.size = htons (sizeof (struct DataMessage) + size);
609 dm->header.type = htons (GNUNET_MESSAGE_TYPE_DATASTORE_DATA);
611 dm->size = htonl (size);
612 dm->type = htonl (type);
613 dm->priority = htonl (priority);
614 dm->anonymity = htonl (anonymity);
615 dm->replication = htonl (0);
616 dm->reserved = htonl (0);
617 dm->expiration = GNUNET_TIME_absolute_hton (expiration);
618 dm->uid = GNUNET_htonll (uid);
620 memcpy (&dm[1], data, size);
621 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
622 "Transmitting `%s' message for `%s' of type %u with expiration %llu (now: %llu)\n",
623 "DATA", GNUNET_h2s (key), type,
624 (unsigned long long) expiration.abs_value,
625 (unsigned long long) GNUNET_TIME_absolute_get ().abs_value);
626 GNUNET_STATISTICS_update (stats, gettext_noop ("# results found"), 1,
628 transmit (client, &dm->header);
629 GNUNET_SERVER_client_drop (client);
635 * Handle RESERVE-message.
638 * @param client identification of the client
639 * @param message the actual message
642 handle_reserve (void *cls, struct GNUNET_SERVER_Client *client,
643 const struct GNUNET_MessageHeader *message)
646 * Static counter to produce reservation identifiers.
648 static int reservation_gen;
650 const struct ReserveMessage *msg = (const struct ReserveMessage *) message;
651 struct ReservationList *e;
652 unsigned long long used;
653 unsigned long long req;
657 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Processing `%s' request\n", "RESERVE");
658 amount = GNUNET_ntohll (msg->amount);
659 entries = ntohl (msg->entries);
660 used = payload + reserved;
662 amount + ((unsigned long long) GNUNET_DATASTORE_ENTRY_OVERHEAD) * entries;
663 if (used + req > quota)
666 used = quota; /* cheat a bit for error message (to avoid negative numbers) */
667 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
669 ("Insufficient space (%llu bytes are available) to satisfy `%s' request for %llu bytes\n"),
670 quota - used, "RESERVE", req);
671 if (cache_size < req)
673 /* TODO: document this in the FAQ; essentially, if this
674 * message happens, the insertion request could be blocked
675 * by less-important content from migration because it is
676 * larger than 1/8th of the overall available space, and
677 * we only reserve 1/8th for "fresh" insertions */
678 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
680 ("The requested amount (%llu bytes) is larger than the cache size (%llu bytes)\n"),
682 transmit_status (client, 0,
684 ("Insufficient space to satisfy request and "
685 "requested amount is larger than cache size"));
689 transmit_status (client, 0,
690 gettext_noop ("Insufficient space to satisfy request"));
695 GNUNET_STATISTICS_set (stats, gettext_noop ("# reserved"), reserved,
697 e = GNUNET_malloc (sizeof (struct ReservationList));
698 e->next = reservations;
702 e->entries = entries;
703 e->rid = ++reservation_gen;
704 if (reservation_gen < 0)
705 reservation_gen = 0; /* wrap around */
706 transmit_status (client, e->rid, NULL);
711 * Handle RELEASE_RESERVE-message.
714 * @param client identification of the client
715 * @param message the actual message
718 handle_release_reserve (void *cls, struct GNUNET_SERVER_Client *client,
719 const struct GNUNET_MessageHeader *message)
721 const struct ReleaseReserveMessage *msg =
722 (const struct ReleaseReserveMessage *) message;
723 struct ReservationList *pos;
724 struct ReservationList *prev;
725 struct ReservationList *next;
726 int rid = ntohl (msg->rid);
727 unsigned long long rem;
729 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Processing `%s' request\n",
733 while (NULL != (pos = next))
744 ((unsigned long long) GNUNET_DATASTORE_ENTRY_OVERHEAD) * pos->entries;
745 GNUNET_assert (reserved >= rem);
747 GNUNET_STATISTICS_set (stats, gettext_noop ("# reserved"), reserved,
749 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
750 "Returning %llu remaining reserved bytes to storage pool\n",
753 transmit_status (client, GNUNET_OK, NULL);
759 transmit_status (client, GNUNET_SYSERR,
760 gettext_noop ("Could not find matching reservation"));
765 * Check that the given message is a valid data message.
767 * @return NULL if the message is not well-formed, otherwise the message
769 static const struct DataMessage *
770 check_data (const struct GNUNET_MessageHeader *message)
774 const struct DataMessage *dm;
776 size = ntohs (message->size);
777 if (size < sizeof (struct DataMessage))
782 dm = (const struct DataMessage *) message;
783 dsize = ntohl (dm->size);
784 if (size != dsize + sizeof (struct DataMessage))
794 * Context for a PUT request used to see if the content is
800 * Client to notify on completion.
802 struct GNUNET_SERVER_Client *client;
804 #if ! HAVE_UNALIGNED_64_ACCESS
808 /* followed by the 'struct DataMessage' */
813 * Actually put the data message.
815 * @param client sender of the message
816 * @param dm message with the data to store
819 execute_put (struct GNUNET_SERVER_Client *client, const struct DataMessage *dm)
825 size = ntohl (dm->size);
828 plugin->api->put (plugin->api->cls, &dm->key, size, &dm[1],
829 ntohl (dm->type), ntohl (dm->priority),
830 ntohl (dm->anonymity), ntohl (dm->replication),
831 GNUNET_TIME_absolute_ntoh (dm->expiration), &msg);
832 if (GNUNET_OK == ret)
834 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes stored"), size,
836 GNUNET_CONTAINER_bloomfilter_add (filter, &dm->key);
837 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
838 "Successfully stored %u bytes of type %u under key `%s'\n",
839 size, ntohl (dm->type), GNUNET_h2s (&dm->key));
841 transmit_status (client, ret, msg);
842 GNUNET_free_non_null (msg);
843 if (quota - reserved - cache_size < payload)
845 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
846 _("Need %llu bytes more space (%llu allowed, using %llu)\n"),
847 (unsigned long long) size + GNUNET_DATASTORE_ENTRY_OVERHEAD,
848 (unsigned long long) (quota - reserved - cache_size),
849 (unsigned long long) payload);
850 manage_space (size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
856 * Function that will check if the given datastore entry
857 * matches the put and if none match executes the put.
859 * @param cls closure, pointer to the client (of type 'struct PutContext').
860 * @param key key for the content
861 * @param size number of bytes in data
862 * @param data content stored
863 * @param type type of the content
864 * @param priority priority of the content
865 * @param anonymity anonymity-level for the content
866 * @param expiration expiration time for the content
867 * @param uid unique identifier for the datum;
868 * maybe 0 if no unique identifier is available
870 * @return GNUNET_OK usually
871 * GNUNET_NO to delete the item
874 check_present (void *cls, const struct GNUNET_HashCode * key, uint32_t size,
875 const void *data, enum GNUNET_BLOCK_Type type, uint32_t priority,
876 uint32_t anonymity, struct GNUNET_TIME_Absolute expiration,
879 struct PutContext *pc = cls;
880 const struct DataMessage *dm;
882 dm = (const struct DataMessage *) &pc[1];
885 execute_put (pc->client, dm);
886 GNUNET_SERVER_client_drop (pc->client);
890 if ((GNUNET_BLOCK_TYPE_FS_DBLOCK == type) ||
891 (GNUNET_BLOCK_TYPE_FS_IBLOCK == type) || ((size == ntohl (dm->size)) &&
893 memcmp (&dm[1], data, size))))
895 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
896 "Result already present in datastore\n");
897 /* FIXME: change API to allow increasing 'replication' counter */
898 if ((ntohl (dm->priority) > 0) ||
899 (GNUNET_TIME_absolute_ntoh (dm->expiration).abs_value >
900 expiration.abs_value))
901 plugin->api->update (plugin->api->cls, uid,
902 (int32_t) ntohl (dm->priority),
903 GNUNET_TIME_absolute_ntoh (dm->expiration), NULL);
904 transmit_status (pc->client, GNUNET_NO, NULL);
905 GNUNET_SERVER_client_drop (pc->client);
910 execute_put (pc->client, dm);
911 GNUNET_SERVER_client_drop (pc->client);
919 * Handle PUT-message.
922 * @param client identification of the client
923 * @param message the actual message
926 handle_put (void *cls, struct GNUNET_SERVER_Client *client,
927 const struct GNUNET_MessageHeader *message)
929 const struct DataMessage *dm = check_data (message);
931 struct ReservationList *pos;
932 struct PutContext *pc;
933 struct GNUNET_HashCode vhash;
936 if ((dm == NULL) || (ntohl (dm->type) == 0))
939 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
942 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
943 "Processing `%s' request for `%s' of type %u\n", "PUT",
944 GNUNET_h2s (&dm->key), ntohl (dm->type));
945 rid = ntohl (dm->rid);
946 size = ntohl (dm->size);
950 while ((NULL != pos) && (rid != pos->rid))
952 GNUNET_break (pos != NULL);
955 GNUNET_break (pos->entries > 0);
956 GNUNET_break (pos->amount >= size);
959 reserved -= (size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
960 GNUNET_STATISTICS_set (stats, gettext_noop ("# reserved"), reserved,
964 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (filter, &dm->key))
966 GNUNET_CRYPTO_hash (&dm[1], size, &vhash);
967 pc = GNUNET_malloc (sizeof (struct PutContext) + size +
968 sizeof (struct DataMessage));
970 GNUNET_SERVER_client_keep (client);
971 memcpy (&pc[1], dm, size + sizeof (struct DataMessage));
972 plugin->api->get_key (plugin->api->cls, 0, &dm->key, &vhash,
973 ntohl (dm->type), &check_present, pc);
976 execute_put (client, dm);
981 * Handle GET-message.
984 * @param client identification of the client
985 * @param message the actual message
988 handle_get (void *cls, struct GNUNET_SERVER_Client *client,
989 const struct GNUNET_MessageHeader *message)
991 const struct GetMessage *msg;
994 size = ntohs (message->size);
995 if ((size != sizeof (struct GetMessage)) &&
996 (size != sizeof (struct GetMessage) - sizeof (struct GNUNET_HashCode)))
999 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1002 msg = (const struct GetMessage *) message;
1003 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1004 "Processing `%s' request for `%s' of type %u\n", "GET",
1005 GNUNET_h2s (&msg->key), ntohl (msg->type));
1006 GNUNET_STATISTICS_update (stats, gettext_noop ("# GET requests received"), 1,
1008 GNUNET_SERVER_client_keep (client);
1009 if ((size == sizeof (struct GetMessage)) &&
1010 (GNUNET_YES != GNUNET_CONTAINER_bloomfilter_test (filter, &msg->key)))
1012 /* don't bother database... */
1013 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1014 "Empty result set for `%s' request for `%s' (bloomfilter).\n",
1015 "GET", GNUNET_h2s (&msg->key));
1016 GNUNET_STATISTICS_update (stats,
1018 ("# requests filtered by bloomfilter"), 1,
1020 transmit_item (client, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS,
1024 plugin->api->get_key (plugin->api->cls, GNUNET_ntohll (msg->offset),
1026 sizeof (struct GetMessage)) ? &msg->key : NULL), NULL,
1027 ntohl (msg->type), &transmit_item, client);
1032 * Handle UPDATE-message.
1034 * @param cls closure
1035 * @param client identification of the client
1036 * @param message the actual message
1039 handle_update (void *cls, struct GNUNET_SERVER_Client *client,
1040 const struct GNUNET_MessageHeader *message)
1042 const struct UpdateMessage *msg;
1046 GNUNET_STATISTICS_update (stats, gettext_noop ("# UPDATE requests received"),
1048 msg = (const struct UpdateMessage *) message;
1050 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Processing `%s' request for %llu\n",
1051 "UPDATE", (unsigned long long) GNUNET_ntohll (msg->uid));
1053 plugin->api->update (plugin->api->cls, GNUNET_ntohll (msg->uid),
1054 (int32_t) ntohl (msg->priority),
1055 GNUNET_TIME_absolute_ntoh (msg->expiration), &emsg);
1056 transmit_status (client, ret, emsg);
1057 GNUNET_free_non_null (emsg);
1062 * Handle GET_REPLICATION-message.
1064 * @param cls closure
1065 * @param client identification of the client
1066 * @param message the actual message
1069 handle_get_replication (void *cls, struct GNUNET_SERVER_Client *client,
1070 const struct GNUNET_MessageHeader *message)
1072 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Processing `%s' request\n",
1074 GNUNET_STATISTICS_update (stats,
1076 ("# GET REPLICATION requests received"), 1,
1078 GNUNET_SERVER_client_keep (client);
1079 plugin->api->get_replication (plugin->api->cls, &transmit_item, client);
1084 * Handle GET_ZERO_ANONYMITY-message.
1086 * @param cls closure
1087 * @param client identification of the client
1088 * @param message the actual message
1091 handle_get_zero_anonymity (void *cls, struct GNUNET_SERVER_Client *client,
1092 const struct GNUNET_MessageHeader *message)
1094 const struct GetZeroAnonymityMessage *msg =
1095 (const struct GetZeroAnonymityMessage *) message;
1096 enum GNUNET_BLOCK_Type type;
1098 type = (enum GNUNET_BLOCK_Type) ntohl (msg->type);
1099 if (type == GNUNET_BLOCK_TYPE_ANY)
1102 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1105 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Processing `%s' request\n",
1106 "GET_ZERO_ANONYMITY");
1107 GNUNET_STATISTICS_update (stats,
1109 ("# GET ZERO ANONYMITY requests received"), 1,
1111 GNUNET_SERVER_client_keep (client);
1112 plugin->api->get_zero_anonymity (plugin->api->cls,
1113 GNUNET_ntohll (msg->offset), type,
1114 &transmit_item, client);
1119 * Callback function that will cause the item that is passed
1120 * in to be deleted (by returning GNUNET_NO).
1123 remove_callback (void *cls, const struct GNUNET_HashCode * key, uint32_t size,
1124 const void *data, enum GNUNET_BLOCK_Type type,
1125 uint32_t priority, uint32_t anonymity,
1126 struct GNUNET_TIME_Absolute expiration, uint64_t uid)
1128 struct GNUNET_SERVER_Client *client = cls;
1132 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1133 "No further matches for `%s' request.\n", "REMOVE");
1134 transmit_status (client, GNUNET_NO, _("Content not found"));
1135 GNUNET_SERVER_client_drop (client);
1136 return GNUNET_OK; /* last item */
1138 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1139 "Item %llu matches `%s' request for key `%s' and type %u.\n",
1140 (unsigned long long) uid, "REMOVE", GNUNET_h2s (key), type);
1141 GNUNET_STATISTICS_update (stats,
1142 gettext_noop ("# bytes removed (explicit request)"),
1144 GNUNET_CONTAINER_bloomfilter_remove (filter, key);
1145 transmit_status (client, GNUNET_OK, NULL);
1146 GNUNET_SERVER_client_drop (client);
1152 * Handle REMOVE-message.
1154 * @param cls closure
1155 * @param client identification of the client
1156 * @param message the actual message
1159 handle_remove (void *cls, struct GNUNET_SERVER_Client *client,
1160 const struct GNUNET_MessageHeader *message)
1162 const struct DataMessage *dm = check_data (message);
1163 struct GNUNET_HashCode vhash;
1168 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1171 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1172 "Processing `%s' request for `%s' of type %u\n", "REMOVE",
1173 GNUNET_h2s (&dm->key), ntohl (dm->type));
1174 GNUNET_STATISTICS_update (stats, gettext_noop ("# REMOVE requests received"),
1176 GNUNET_SERVER_client_keep (client);
1177 GNUNET_CRYPTO_hash (&dm[1], ntohl (dm->size), &vhash);
1178 plugin->api->get_key (plugin->api->cls, 0, &dm->key, &vhash,
1179 (enum GNUNET_BLOCK_Type) ntohl (dm->type),
1180 &remove_callback, client);
1185 * Handle DROP-message.
1187 * @param cls closure
1188 * @param client identification of the client
1189 * @param message the actual message
1192 handle_drop (void *cls, struct GNUNET_SERVER_Client *client,
1193 const struct GNUNET_MessageHeader *message)
1195 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Processing `%s' request\n", "DROP");
1196 do_drop = GNUNET_YES;
1197 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1202 * Function called by plugins to notify us about a
1203 * change in their disk utilization.
1205 * @param cls closure (NULL)
1206 * @param delta change in disk utilization,
1207 * 0 for "reset to empty"
1210 disk_utilization_change_cb (void *cls, int delta)
1212 if ((delta < 0) && (payload < -delta))
1214 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1216 ("Datastore payload inaccurate (%lld < %lld). Trying to fix.\n"),
1217 (long long) payload, (long long) -delta);
1218 payload = plugin->api->estimate_size (plugin->api->cls);
1224 if (lastSync >= MAX_STAT_SYNC_LAG)
1230 * Callback function to process statistic values.
1232 * @param cls closure (struct Plugin*)
1233 * @param subsystem name of subsystem that created the statistic
1234 * @param name the name of the datum
1235 * @param value the current value
1236 * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
1237 * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
1240 process_stat_in (void *cls, const char *subsystem, const char *name,
1241 uint64_t value, int is_persistent)
1243 GNUNET_assert (stats_worked == GNUNET_NO);
1244 stats_worked = GNUNET_YES;
1246 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1247 "Notification from statistics about existing payload (%llu), new payload is %llu\n",
1254 process_stat_done (void *cls, int success)
1256 struct DatastorePlugin *plugin = cls;
1259 if (stats_worked == GNUNET_NO)
1260 payload = plugin->api->estimate_size (plugin->api->cls);
1265 * Load the datastore plugin.
1267 static struct DatastorePlugin *
1270 struct DatastorePlugin *ret;
1273 ret = GNUNET_malloc (sizeof (struct DatastorePlugin));
1275 ret->env.duc = &disk_utilization_change_cb;
1276 ret->env.cls = NULL;
1277 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Loading `%s' datastore plugin\n"),
1279 GNUNET_asprintf (&libname, "libgnunet_plugin_datastore_%s", plugin_name);
1280 ret->short_name = GNUNET_strdup (plugin_name);
1281 ret->lib_name = libname;
1282 ret->api = GNUNET_PLUGIN_load (libname, &ret->env);
1283 if (ret->api == NULL)
1285 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1286 _("Failed to load datastore plugin for `%s'\n"), plugin_name);
1287 GNUNET_free (ret->short_name);
1288 GNUNET_free (libname);
1297 * Function called when the service shuts
1298 * down. Unloads our datastore plugin.
1300 * @param plug plugin to unload
1303 unload_plugin (struct DatastorePlugin *plug)
1305 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1306 "Datastore service is unloading plugin...\n");
1307 GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
1308 GNUNET_free (plug->lib_name);
1309 GNUNET_free (plug->short_name);
1311 GNUNET_free (quota_stat_name);
1312 quota_stat_name = NULL;
1317 * Final task run after shutdown. Unloads plugins and disconnects us from
1321 unload_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1325 if (GNUNET_YES == do_drop)
1326 plugin->api->drop (plugin->api->cls);
1327 unload_plugin (plugin);
1331 GNUNET_CONTAINER_bloomfilter_free (filter);
1334 if (stat_get != NULL)
1336 GNUNET_STATISTICS_get_cancel (stat_get);
1341 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
1344 GNUNET_free_non_null (plugin_name);
1350 * Last task run during shutdown. Disconnects us from
1351 * the transport and core.
1354 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1356 struct TransmitCallbackContext *tcc;
1358 cleaning_done = GNUNET_YES;
1359 while (NULL != (tcc = tcc_head))
1361 GNUNET_CONTAINER_DLL_remove (tcc_head, tcc_tail, tcc);
1362 if (tcc->th != NULL)
1364 GNUNET_SERVER_notify_transmit_ready_cancel (tcc->th);
1365 GNUNET_SERVER_client_drop (tcc->client);
1367 GNUNET_free (tcc->msg);
1370 if (expired_kill_task != GNUNET_SCHEDULER_NO_TASK)
1372 GNUNET_SCHEDULER_cancel (expired_kill_task);
1373 expired_kill_task = GNUNET_SCHEDULER_NO_TASK;
1375 GNUNET_SCHEDULER_add_continuation (&unload_task, NULL,
1376 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
1381 * Function that removes all active reservations made
1382 * by the given client and releases the space for other
1385 * @param cls closure
1386 * @param client identification of the client
1389 cleanup_reservations (void *cls, struct GNUNET_SERVER_Client *client)
1391 struct ReservationList *pos;
1392 struct ReservationList *prev;
1393 struct ReservationList *next;
1402 if (pos->client == client)
1405 reservations = next;
1408 reserved -= pos->amount + pos->entries * GNUNET_DATASTORE_ENTRY_OVERHEAD;
1417 GNUNET_STATISTICS_set (stats, gettext_noop ("# reserved"), reserved,
1423 * Adds a given key to the bloomfilter 'count' times.
1425 * @param cls the bloomfilter
1426 * @param key key to add
1427 * @param count number of times to add key
1430 add_key_to_bloomfilter (void *cls,
1431 const struct GNUNET_HashCode *key,
1434 struct GNUNET_CONTAINER_BloomFilter *bf = cls;
1436 GNUNET_CONTAINER_bloomfilter_add (bf, key);
1441 * Process datastore requests.
1443 * @param cls closure
1444 * @param server the initialized server
1445 * @param c configuration to use
1448 run (void *cls, struct GNUNET_SERVER_Handle *server,
1449 const struct GNUNET_CONFIGURATION_Handle *c)
1451 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1452 {&handle_reserve, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_RESERVE,
1453 sizeof (struct ReserveMessage)},
1454 {&handle_release_reserve, NULL,
1455 GNUNET_MESSAGE_TYPE_DATASTORE_RELEASE_RESERVE,
1456 sizeof (struct ReleaseReserveMessage)},
1457 {&handle_put, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_PUT, 0},
1458 {&handle_update, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_UPDATE,
1459 sizeof (struct UpdateMessage)},
1460 {&handle_get, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_GET, 0},
1461 {&handle_get_replication, NULL,
1462 GNUNET_MESSAGE_TYPE_DATASTORE_GET_REPLICATION,
1463 sizeof (struct GNUNET_MessageHeader)},
1464 {&handle_get_zero_anonymity, NULL,
1465 GNUNET_MESSAGE_TYPE_DATASTORE_GET_ZERO_ANONYMITY,
1466 sizeof (struct GetZeroAnonymityMessage)},
1467 {&handle_remove, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_REMOVE, 0},
1468 {&handle_drop, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_DROP,
1469 sizeof (struct GNUNET_MessageHeader)},
1474 unsigned int bf_size;
1479 GNUNET_CONFIGURATION_get_value_string (cfg, "DATASTORE", "DATABASE",
1482 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1483 _("No `%s' specified for `%s' in configuration!\n"), "DATABASE",
1487 GNUNET_asprintf ("a_stat_name,
1488 _("# bytes used in file-sharing datastore `%s'"),
1491 GNUNET_CONFIGURATION_get_value_size (cfg, "DATASTORE", "QUOTA", "a))
1493 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1494 _("No `%s' specified for `%s' in configuration!\n"), "QUOTA",
1498 stats = GNUNET_STATISTICS_create ("datastore", cfg);
1499 GNUNET_STATISTICS_set (stats, gettext_noop ("# quota"), quota, GNUNET_NO);
1500 cache_size = quota / 8; /* Or should we make this an option? */
1501 GNUNET_STATISTICS_set (stats, gettext_noop ("# cache size"), cache_size,
1503 if (quota / (32 * 1024LL) > (1 << 31))
1504 bf_size = (1 << 31); /* absolute limit: ~2 GB, beyond that BF just won't help anyway */
1506 bf_size = quota / (32 * 1024LL); /* 8 bit per entry, 1 bit per 32 kb in DB */
1509 GNUNET_CONFIGURATION_get_value_filename (cfg, "DATASTORE", "BLOOMFILTER",
1511 (GNUNET_OK != GNUNET_DISK_directory_create_for_file (fn)))
1513 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1514 _("Could not use specified filename `%s' for bloomfilter.\n"),
1515 fn != NULL ? fn : "");
1516 GNUNET_free_non_null (fn);
1521 GNUNET_asprintf (&pfn, "%s.%s", fn, plugin_name);
1522 if (GNUNET_YES == GNUNET_DISK_file_test (pfn))
1524 filter = GNUNET_CONTAINER_bloomfilter_load (pfn, bf_size, 5); /* approx. 3% false positives at max use */
1527 /* file exists but not valid, remove and try again, but refresh */
1528 if (0 != UNLINK (pfn))
1530 /* failed to remove, run without file */
1531 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1532 _("Failed to remove bogus bloomfilter file `%s'\n"),
1536 filter = GNUNET_CONTAINER_bloomfilter_load (NULL, bf_size, 5); /* approx. 3% false positives at max use */
1537 refresh_bf = GNUNET_YES;
1541 /* try again after remove */
1542 filter = GNUNET_CONTAINER_bloomfilter_load (pfn, bf_size, 5); /* approx. 3% false positives at max use */
1543 refresh_bf = GNUNET_YES;
1546 /* failed yet again, give up on using file */
1547 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1548 _("Failed to remove bogus bloomfilter file `%s'\n"),
1552 filter = GNUNET_CONTAINER_bloomfilter_init (NULL, bf_size, 5); /* approx. 3% false positives at max use */
1558 /* normal case: have an existing valid bf file, no need to refresh */
1559 refresh_bf = GNUNET_NO;
1564 filter = GNUNET_CONTAINER_bloomfilter_load (pfn, bf_size, 5); /* approx. 3% false positives at max use */
1565 refresh_bf = GNUNET_YES;
1571 filter = GNUNET_CONTAINER_bloomfilter_init (NULL, bf_size, 5); /* approx. 3% false positives at max use */
1572 refresh_bf = GNUNET_YES;
1574 GNUNET_free_non_null (fn);
1577 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1578 _("Failed to initialize bloomfilter.\n"));
1581 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
1586 plugin = load_plugin ();
1589 GNUNET_CONTAINER_bloomfilter_free (filter);
1593 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
1599 GNUNET_STATISTICS_get (stats, "datastore", quota_stat_name,
1600 GNUNET_TIME_UNIT_SECONDS, &process_stat_done,
1601 &process_stat_in, plugin);
1602 GNUNET_SERVER_disconnect_notify (server, &cleanup_reservations, NULL);
1603 GNUNET_SERVER_add_handlers (server, handlers);
1604 if (GNUNET_YES == refresh_bf)
1606 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1607 _("Rebuilding bloomfilter. Please be patient.\n"));
1608 if (NULL != plugin->api->get_keys)
1609 plugin->api->get_keys (plugin->api->cls, &add_key_to_bloomfilter, filter);
1611 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1612 _("Plugin does not support get_keys function. Please fix!\n"));
1614 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1615 _("Bloomfilter construction complete.\n"));
1618 GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE,
1619 &delete_expired, NULL);
1620 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &cleaning_task,
1626 * The main function for the datastore service.
1628 * @param argc number of arguments from the command line
1629 * @param argv command line arguments
1630 * @return 0 ok, 1 on error
1633 main (int argc, char *const *argv)
1639 GNUNET_SERVICE_run (argc, argv, "datastore", GNUNET_SERVICE_OPTION_NONE,
1640 &run, NULL)) ? 0 : 1;
1645 /* end of gnunet-service-datastore.c */