2 This file is part of GNUnet
3 Copyright (C) 2004-2014 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/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 * Name of our plugin.
147 static char *plugin_name;
152 static const struct GNUNET_CONFIGURATION_Handle *cfg;
155 * Handle for reporting statistics.
157 static struct GNUNET_STATISTICS_Handle *stats;
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 * Identity of the task that is used to delete
182 static struct GNUNET_SCHEDULER_Task * expired_kill_task;
185 * Minimum time that content should have to not be discarded instantly
186 * (time stamp of any content that we've been discarding recently to
187 * stay below the quota). FOREVER if we had to expire content with
190 static struct GNUNET_TIME_Absolute min_expiration;
193 * How much space are we allowed to use?
195 static unsigned long long quota;
198 * Should the database be dropped on exit?
203 * Should we refresh the BF when the DB is loaded?
205 static int refresh_bf;
208 * Number of updates that were made to the
209 * payload value since we last synchronized
210 * it with the statistics service.
212 static unsigned int last_sync;
215 * Did we get an answer from statistics?
217 static int stats_worked;
221 * Synchronize our utilization statistics with the
222 * statistics service.
227 GNUNET_STATISTICS_set (stats, quota_stat_name, payload, GNUNET_YES);
228 GNUNET_STATISTICS_set (stats, "# utilization by current datastore", payload, GNUNET_NO);
234 * Context for transmitting replies to clients.
236 struct TransmitCallbackContext
240 * We keep these in a doubly-linked list (for cleanup).
242 struct TransmitCallbackContext *next;
245 * We keep these in a doubly-linked list (for cleanup).
247 struct TransmitCallbackContext *prev;
250 * The message that we're asked to transmit.
252 struct GNUNET_MessageHeader *msg;
255 * Handle for the transmission request.
257 struct GNUNET_SERVER_TransmitHandle *th;
260 * Client that we are transmitting to.
262 struct GNUNET_SERVER_Client *client;
268 * Head of the doubly-linked list (for cleanup).
270 static struct TransmitCallbackContext *tcc_head;
273 * Tail of the doubly-linked list (for cleanup).
275 static struct TransmitCallbackContext *tcc_tail;
278 * Have we already cleaned up the TCCs and are hence no longer
279 * willing (or able) to transmit anything to anyone?
281 static int cleaning_done;
284 * Handle for pending get request.
286 static struct GNUNET_STATISTICS_GetHandle *stat_get;
289 * Handle to our server.
291 static struct GNUNET_SERVER_Handle *server;
294 * Task that is used to remove expired entries from
295 * the datastore. This task will schedule itself
296 * again automatically to always delete all expired
299 * @param cls not used
300 * @param tc task context
303 delete_expired (void *cls,
304 const struct GNUNET_SCHEDULER_TaskContext *tc);
308 * Iterate over the expired items stored in the datastore.
309 * Delete all expired items; once we have processed all
310 * expired items, re-schedule the "delete_expired" task.
312 * @param cls not used
313 * @param key key for the content
314 * @param size number of bytes in data
315 * @param data content stored
316 * @param type type of the content
317 * @param priority priority of the content
318 * @param anonymity anonymity-level for the content
319 * @param expiration expiration time for the content
320 * @param uid unique identifier for the datum;
321 * maybe 0 if no unique identifier is available
323 * @return #GNUNET_SYSERR to abort the iteration, #GNUNET_OK to continue
324 * (continue on call to "next", of course),
325 * #GNUNET_NO to delete the item and continue (if supported)
328 expired_processor (void *cls,
329 const struct GNUNET_HashCode *key,
332 enum GNUNET_BLOCK_Type type,
335 struct GNUNET_TIME_Absolute expiration,
338 struct GNUNET_TIME_Absolute now;
343 GNUNET_SCHEDULER_add_delayed_with_priority (MAX_EXPIRE_DELAY,
344 GNUNET_SCHEDULER_PRIORITY_IDLE,
345 &delete_expired, NULL);
346 return GNUNET_SYSERR;
348 now = GNUNET_TIME_absolute_get ();
349 if (expiration.abs_value_us > now.abs_value_us)
351 /* finished processing */
353 GNUNET_SCHEDULER_add_delayed_with_priority (MAX_EXPIRE_DELAY,
354 GNUNET_SCHEDULER_PRIORITY_IDLE,
355 &delete_expired, NULL);
356 return GNUNET_SYSERR;
358 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
359 "Deleting content `%s' of type %u that expired %s ago\n",
360 GNUNET_h2s (key), type,
361 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_difference (expiration,
364 min_expiration = now;
365 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes expired"), size,
367 GNUNET_CONTAINER_bloomfilter_remove (filter, key);
369 GNUNET_SCHEDULER_add_delayed_with_priority (MIN_EXPIRE_DELAY,
370 GNUNET_SCHEDULER_PRIORITY_IDLE,
371 &delete_expired, NULL);
377 * Task that is used to remove expired entries from
378 * the datastore. This task will schedule itself
379 * again automatically to always delete all expired
382 * @param cls not used
383 * @param tc task context
386 delete_expired (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
388 expired_kill_task = NULL;
389 plugin->api->get_expiration (plugin->api->cls, &expired_processor, NULL);
394 * An iterator over a set of items stored in the datastore
395 * that deletes until we're happy with respect to our quota.
398 * @param key key for the content
399 * @param size number of bytes in data
400 * @param data content stored
401 * @param type type of the content
402 * @param priority priority of the content
403 * @param anonymity anonymity-level for the content
404 * @param expiration expiration time for the content
405 * @param uid unique identifier for the datum;
406 * maybe 0 if no unique identifier is available
408 * @return GNUNET_SYSERR to abort the iteration, GNUNET_OK to continue
409 * (continue on call to "next", of course),
410 * GNUNET_NO to delete the item and continue (if supported)
413 quota_processor (void *cls, const struct GNUNET_HashCode * key, uint32_t size,
414 const void *data, enum GNUNET_BLOCK_Type type,
415 uint32_t priority, uint32_t anonymity,
416 struct GNUNET_TIME_Absolute expiration, uint64_t uid)
418 unsigned long long *need = cls;
421 return GNUNET_SYSERR;
422 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
423 "Deleting %llu bytes of low-priority (%u) content `%s' of type %u at %s prior to expiration (still trying to free another %llu bytes)\n",
424 (unsigned long long) (size + GNUNET_DATASTORE_ENTRY_OVERHEAD),
425 (unsigned int) priority,
426 GNUNET_h2s (key), type,
427 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining (expiration),
430 if (size + GNUNET_DATASTORE_ENTRY_OVERHEAD > *need)
433 *need -= size + GNUNET_DATASTORE_ENTRY_OVERHEAD;
435 min_expiration = GNUNET_TIME_UNIT_FOREVER_ABS;
437 min_expiration = expiration;
438 GNUNET_STATISTICS_update (stats,
439 gettext_noop ("# bytes purged (low-priority)"),
441 GNUNET_CONTAINER_bloomfilter_remove (filter, key);
447 * Manage available disk space by running tasks
448 * that will discard content if necessary. This
449 * function will be run whenever a request for
450 * "need" bytes of storage could only be satisfied
451 * by eating into the "cache" (and we want our cache
454 * @param need number of bytes of content that were
455 * placed into the "cache" (and hence the
456 * number of bytes that should be removed).
459 manage_space (unsigned long long need)
461 unsigned long long last;
463 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
464 "Asked to free up %llu bytes of cache space\n", need);
466 while ((need > 0) && (last != need))
469 plugin->api->get_expiration (plugin->api->cls, "a_processor, &need);
475 * Function called to notify a client about the socket
476 * begin ready to queue more data. "buf" will be
477 * NULL and "size" zero if the socket was closed for
478 * writing in the meantime.
481 * @param size number of bytes available in buf
482 * @param buf where the callee should write the message
483 * @return number of bytes written to buf
486 transmit_callback (void *cls, size_t size, void *buf)
488 struct TransmitCallbackContext *tcc = cls;
492 GNUNET_CONTAINER_DLL_remove (tcc_head, tcc_tail, tcc);
493 msize = ntohs (tcc->msg->size);
496 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
497 _("Transmission to client failed!\n"));
498 GNUNET_SERVER_receive_done (tcc->client, GNUNET_SYSERR);
499 GNUNET_SERVER_client_drop (tcc->client);
500 GNUNET_free (tcc->msg);
504 GNUNET_assert (size >= msize);
505 memcpy (buf, tcc->msg, msize);
506 GNUNET_SERVER_receive_done (tcc->client, GNUNET_OK);
507 GNUNET_SERVER_client_drop (tcc->client);
508 GNUNET_free (tcc->msg);
515 * Transmit the given message to the client.
517 * @param client target of the message
518 * @param msg message to transmit, will be freed!
521 transmit (struct GNUNET_SERVER_Client *client, struct GNUNET_MessageHeader *msg)
523 struct TransmitCallbackContext *tcc;
525 if (GNUNET_YES == cleaning_done)
527 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
528 _("Shutdown in progress, aborting transmission.\n"));
529 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
533 tcc = GNUNET_new (struct TransmitCallbackContext);
535 tcc->client = client;
538 GNUNET_SERVER_notify_transmit_ready (client, ntohs (msg->size),
539 GNUNET_TIME_UNIT_FOREVER_REL,
540 &transmit_callback, tcc)))
543 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
548 GNUNET_SERVER_client_keep (client);
549 GNUNET_CONTAINER_DLL_insert (tcc_head, tcc_tail, tcc);
554 * Transmit a status code to the client.
556 * @param client receiver of the response
557 * @param code status code
558 * @param msg optional error message (can be NULL)
561 transmit_status (struct GNUNET_SERVER_Client *client, int code, const char *msg)
563 struct StatusMessage *sm;
566 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
567 "Transmitting `%s' message with value %d and message `%s'\n",
568 "STATUS", code, msg != NULL ? msg : "(none)");
569 slen = (msg == NULL) ? 0 : strlen (msg) + 1;
570 sm = GNUNET_malloc (sizeof (struct StatusMessage) + slen);
571 sm->header.size = htons (sizeof (struct StatusMessage) + slen);
572 sm->header.type = htons (GNUNET_MESSAGE_TYPE_DATASTORE_STATUS);
573 sm->status = htonl (code);
574 sm->min_expiration = GNUNET_TIME_absolute_hton (min_expiration);
576 memcpy (&sm[1], msg, slen);
577 transmit (client, &sm->header);
582 * Function that will transmit the given datastore entry
585 * @param cls closure, pointer to the client (of type GNUNET_SERVER_Client).
586 * @param key key for the content
587 * @param size number of bytes in data
588 * @param data content stored
589 * @param type type of the content
590 * @param priority priority of the content
591 * @param anonymity anonymity-level for the content
592 * @param expiration expiration time for the content
593 * @param uid unique identifier for the datum;
594 * maybe 0 if no unique identifier is available
596 * @return GNUNET_SYSERR to abort the iteration, GNUNET_OK to continue,
597 * GNUNET_NO to delete the item and continue (if supported)
600 transmit_item (void *cls, const struct GNUNET_HashCode * key, uint32_t size,
601 const void *data, enum GNUNET_BLOCK_Type type, uint32_t priority,
602 uint32_t anonymity, struct GNUNET_TIME_Absolute expiration,
605 struct GNUNET_SERVER_Client *client = cls;
606 struct GNUNET_MessageHeader *end;
607 struct DataMessage *dm;
611 /* transmit 'DATA_END' */
612 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transmitting `%s' message\n",
614 end = GNUNET_new (struct GNUNET_MessageHeader);
615 end->size = htons (sizeof (struct GNUNET_MessageHeader));
616 end->type = htons (GNUNET_MESSAGE_TYPE_DATASTORE_DATA_END);
617 transmit (client, end);
618 GNUNET_SERVER_client_drop (client);
621 GNUNET_assert (sizeof (struct DataMessage) + size <
622 GNUNET_SERVER_MAX_MESSAGE_SIZE);
623 dm = GNUNET_malloc (sizeof (struct DataMessage) + size);
624 dm->header.size = htons (sizeof (struct DataMessage) + size);
625 dm->header.type = htons (GNUNET_MESSAGE_TYPE_DATASTORE_DATA);
627 dm->size = htonl (size);
628 dm->type = htonl (type);
629 dm->priority = htonl (priority);
630 dm->anonymity = htonl (anonymity);
631 dm->replication = htonl (0);
632 dm->reserved = htonl (0);
633 dm->expiration = GNUNET_TIME_absolute_hton (expiration);
634 dm->uid = GNUNET_htonll (uid);
636 memcpy (&dm[1], data, size);
637 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
638 "Transmitting `%s' message for `%s' of type %u with expiration %s (in: %s)\n",
639 "DATA", GNUNET_h2s (key), type,
640 GNUNET_STRINGS_absolute_time_to_string (expiration),
641 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining (expiration),
643 GNUNET_STATISTICS_update (stats, gettext_noop ("# results found"), 1,
645 transmit (client, &dm->header);
646 GNUNET_SERVER_client_drop (client);
652 * Handle RESERVE-message.
655 * @param client identification of the client
656 * @param message the actual message
659 handle_reserve (void *cls, struct GNUNET_SERVER_Client *client,
660 const struct GNUNET_MessageHeader *message)
663 * Static counter to produce reservation identifiers.
665 static int reservation_gen;
667 const struct ReserveMessage *msg = (const struct ReserveMessage *) message;
668 struct ReservationList *e;
669 unsigned long long used;
670 unsigned long long req;
674 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Processing `%s' request\n", "RESERVE");
675 amount = GNUNET_ntohll (msg->amount);
676 entries = ntohl (msg->entries);
677 used = payload + reserved;
679 amount + ((unsigned long long) GNUNET_DATASTORE_ENTRY_OVERHEAD) * entries;
680 if (used + req > quota)
683 used = quota; /* cheat a bit for error message (to avoid negative numbers) */
684 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
686 ("Insufficient space (%llu bytes are available) to satisfy `%s' request for %llu bytes\n"),
687 quota - used, "RESERVE", req);
688 if (cache_size < req)
690 /* TODO: document this in the FAQ; essentially, if this
691 * message happens, the insertion request could be blocked
692 * by less-important content from migration because it is
693 * larger than 1/8th of the overall available space, and
694 * we only reserve 1/8th for "fresh" insertions */
695 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
697 ("The requested amount (%llu bytes) is larger than the cache size (%llu bytes)\n"),
699 transmit_status (client, 0,
701 ("Insufficient space to satisfy request and "
702 "requested amount is larger than cache size"));
706 transmit_status (client, 0,
707 gettext_noop ("Insufficient space to satisfy request"));
712 GNUNET_STATISTICS_set (stats, gettext_noop ("# reserved"), reserved,
714 e = GNUNET_new (struct ReservationList);
715 e->next = reservations;
719 e->entries = entries;
720 e->rid = ++reservation_gen;
721 if (reservation_gen < 0)
722 reservation_gen = 0; /* wrap around */
723 transmit_status (client, e->rid, NULL);
728 * Handle RELEASE_RESERVE-message.
731 * @param client identification of the client
732 * @param message the actual message
735 handle_release_reserve (void *cls,
736 struct GNUNET_SERVER_Client *client,
737 const struct GNUNET_MessageHeader *message)
739 const struct ReleaseReserveMessage *msg =
740 (const struct ReleaseReserveMessage *) message;
741 struct ReservationList *pos;
742 struct ReservationList *prev;
743 struct ReservationList *next;
744 int rid = ntohl (msg->rid);
745 unsigned long long rem;
747 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
748 "Processing `%s' request\n",
752 while (NULL != (pos = next))
763 ((unsigned long long) GNUNET_DATASTORE_ENTRY_OVERHEAD) * pos->entries;
764 GNUNET_assert (reserved >= rem);
766 GNUNET_STATISTICS_set (stats,
767 gettext_noop ("# reserved"), reserved,
769 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
770 "Returning %llu remaining reserved bytes to storage pool\n",
773 transmit_status (client, GNUNET_OK, NULL);
779 transmit_status (client, GNUNET_SYSERR,
780 gettext_noop ("Could not find matching reservation"));
785 * Check that the given message is a valid data message.
787 * @return NULL if the message is not well-formed, otherwise the message
789 static const struct DataMessage *
790 check_data (const struct GNUNET_MessageHeader *message)
794 const struct DataMessage *dm;
796 size = ntohs (message->size);
797 if (size < sizeof (struct DataMessage))
802 dm = (const struct DataMessage *) message;
803 dsize = ntohl (dm->size);
804 if (size != dsize + sizeof (struct DataMessage))
814 * Context for a PUT request used to see if the content is
820 * Client to notify on completion.
822 struct GNUNET_SERVER_Client *client;
824 #if ! HAVE_UNALIGNED_64_ACCESS
828 /* followed by the 'struct DataMessage' */
833 put_continuation (void *cls, const struct GNUNET_HashCode *key, uint32_t size,
834 int status, char *msg)
836 struct GNUNET_SERVER_Client *client = cls;
838 if (GNUNET_OK == status)
840 GNUNET_STATISTICS_update (stats,
841 gettext_noop ("# bytes stored"), size,
843 GNUNET_CONTAINER_bloomfilter_add (filter, key);
844 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
845 "Successfully stored %u bytes under key `%s'\n",
846 size, GNUNET_h2s (key));
848 transmit_status (client, status, msg);
849 GNUNET_SERVER_client_drop (client);
850 if (quota - reserved - cache_size < payload)
852 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
853 _("Need %llu bytes more space (%llu allowed, using %llu)\n"),
854 (unsigned long long) size + GNUNET_DATASTORE_ENTRY_OVERHEAD,
855 (unsigned long long) (quota - reserved - cache_size),
856 (unsigned long long) payload);
857 manage_space (size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
862 * Actually put the data message.
864 * @param client sender of the message
865 * @param dm message with the data to store
868 execute_put (struct GNUNET_SERVER_Client *client, const struct DataMessage *dm)
870 GNUNET_SERVER_client_keep (client);
871 plugin->api->put (plugin->api->cls, &dm->key, ntohl (dm->size), &dm[1],
872 ntohl (dm->type), ntohl (dm->priority),
873 ntohl (dm->anonymity), ntohl (dm->replication),
874 GNUNET_TIME_absolute_ntoh (dm->expiration),
875 &put_continuation, client);
880 check_present_continuation (void *cls, int status, char *msg)
882 struct GNUNET_SERVER_Client *client = cls;
884 transmit_status (client, GNUNET_NO, NULL);
885 GNUNET_SERVER_client_drop (client);
890 * Function that will check if the given datastore entry
891 * matches the put and if none match executes the put.
893 * @param cls closure, pointer to the client (of type 'struct PutContext').
894 * @param key key for the content
895 * @param size number of bytes in data
896 * @param data content stored
897 * @param type type of the content
898 * @param priority priority of the content
899 * @param anonymity anonymity-level for the content
900 * @param expiration expiration time for the content
901 * @param uid unique identifier for the datum;
902 * maybe 0 if no unique identifier is available
904 * @return GNUNET_OK usually
905 * GNUNET_NO to delete the item
908 check_present (void *cls, const struct GNUNET_HashCode * key, uint32_t size,
909 const void *data, enum GNUNET_BLOCK_Type type, uint32_t priority,
910 uint32_t anonymity, struct GNUNET_TIME_Absolute expiration,
913 struct PutContext *pc = cls;
914 const struct DataMessage *dm;
916 dm = (const struct DataMessage *) &pc[1];
919 execute_put (pc->client, dm);
920 GNUNET_SERVER_client_drop (pc->client);
924 if ((GNUNET_BLOCK_TYPE_FS_DBLOCK == type) ||
925 (GNUNET_BLOCK_TYPE_FS_IBLOCK == type) || ((size == ntohl (dm->size)) &&
927 memcmp (&dm[1], data, size))))
929 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
930 "Result already present in datastore\n");
931 /* FIXME: change API to allow increasing 'replication' counter */
932 if ((ntohl (dm->priority) > 0) ||
933 (GNUNET_TIME_absolute_ntoh (dm->expiration).abs_value_us >
934 expiration.abs_value_us))
935 plugin->api->update (plugin->api->cls, uid,
936 (int32_t) ntohl (dm->priority),
937 GNUNET_TIME_absolute_ntoh (dm->expiration),
938 check_present_continuation, pc->client);
941 transmit_status (pc->client, GNUNET_NO, NULL);
942 GNUNET_SERVER_client_drop (pc->client);
948 execute_put (pc->client, dm);
949 GNUNET_SERVER_client_drop (pc->client);
957 * Handle PUT-message.
960 * @param client identification of the client
961 * @param message the actual message
964 handle_put (void *cls, struct GNUNET_SERVER_Client *client,
965 const struct GNUNET_MessageHeader *message)
967 const struct DataMessage *dm = check_data (message);
969 struct ReservationList *pos;
970 struct PutContext *pc;
971 struct GNUNET_HashCode vhash;
974 if ((dm == NULL) || (ntohl (dm->type) == 0))
977 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
980 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
981 "Processing `%s' request for `%s' of type %u\n", "PUT",
982 GNUNET_h2s (&dm->key), ntohl (dm->type));
983 rid = ntohl (dm->rid);
984 size = ntohl (dm->size);
988 while ((NULL != pos) && (rid != pos->rid))
990 GNUNET_break (pos != NULL);
993 GNUNET_break (pos->entries > 0);
994 GNUNET_break (pos->amount >= size);
997 reserved -= (size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
998 GNUNET_STATISTICS_set (stats,
999 gettext_noop ("# reserved"), reserved,
1003 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (filter, &dm->key))
1005 GNUNET_CRYPTO_hash (&dm[1], size, &vhash);
1006 pc = GNUNET_malloc (sizeof (struct PutContext) + size +
1007 sizeof (struct DataMessage));
1008 pc->client = client;
1009 GNUNET_SERVER_client_keep (client);
1010 memcpy (&pc[1], dm, size + sizeof (struct DataMessage));
1011 plugin->api->get_key (plugin->api->cls, 0, &dm->key, &vhash,
1012 ntohl (dm->type), &check_present, pc);
1015 execute_put (client, dm);
1020 * Handle GET-message.
1022 * @param cls closure
1023 * @param client identification of the client
1024 * @param message the actual message
1027 handle_get (void *cls, struct GNUNET_SERVER_Client *client,
1028 const struct GNUNET_MessageHeader *message)
1030 const struct GetMessage *msg;
1033 size = ntohs (message->size);
1034 if ((size != sizeof (struct GetMessage)) &&
1035 (size != sizeof (struct GetMessage) - sizeof (struct GNUNET_HashCode)))
1038 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1041 msg = (const struct GetMessage *) message;
1042 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1043 "Processing `%s' request for `%s' of type %u\n", "GET",
1044 GNUNET_h2s (&msg->key), ntohl (msg->type));
1045 GNUNET_STATISTICS_update (stats,
1046 gettext_noop ("# GET requests received"), 1,
1048 GNUNET_SERVER_client_keep (client);
1049 if ((size == sizeof (struct GetMessage)) &&
1050 (GNUNET_YES != GNUNET_CONTAINER_bloomfilter_test (filter, &msg->key)))
1052 /* don't bother database... */
1053 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1054 "Empty result set for `%s' request for `%s' (bloomfilter).\n",
1055 "GET", GNUNET_h2s (&msg->key));
1056 GNUNET_STATISTICS_update (stats,
1058 ("# requests filtered by bloomfilter"), 1,
1060 transmit_item (client, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS,
1064 plugin->api->get_key (plugin->api->cls, GNUNET_ntohll (msg->offset),
1066 sizeof (struct GetMessage)) ? &msg->key : NULL), NULL,
1067 ntohl (msg->type), &transmit_item, client);
1072 update_continuation (void *cls, int status, char *msg)
1074 struct GNUNET_SERVER_Client *client = cls;
1076 transmit_status (client, status, msg);
1077 GNUNET_SERVER_client_drop (client);
1082 * Handle UPDATE-message.
1084 * @param cls closure
1085 * @param client identification of the client
1086 * @param message the actual message
1089 handle_update (void *cls, struct GNUNET_SERVER_Client *client,
1090 const struct GNUNET_MessageHeader *message)
1092 const struct UpdateMessage *msg;
1094 GNUNET_STATISTICS_update (stats, gettext_noop ("# UPDATE requests received"),
1096 msg = (const struct UpdateMessage *) message;
1097 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Processing `%s' request for %llu\n",
1098 "UPDATE", (unsigned long long) GNUNET_ntohll (msg->uid));
1099 GNUNET_SERVER_client_keep (client);
1100 plugin->api->update (plugin->api->cls, GNUNET_ntohll (msg->uid),
1101 (int32_t) ntohl (msg->priority),
1102 GNUNET_TIME_absolute_ntoh (msg->expiration),
1103 update_continuation, client);
1108 * Handle GET_REPLICATION-message.
1110 * @param cls closure
1111 * @param client identification of the client
1112 * @param message the actual message
1115 handle_get_replication (void *cls, struct GNUNET_SERVER_Client *client,
1116 const struct GNUNET_MessageHeader *message)
1118 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Processing `%s' request\n",
1120 GNUNET_STATISTICS_update (stats,
1122 ("# GET REPLICATION requests received"), 1,
1124 GNUNET_SERVER_client_keep (client);
1125 plugin->api->get_replication (plugin->api->cls, &transmit_item, client);
1130 * Handle GET_ZERO_ANONYMITY-message.
1132 * @param cls closure
1133 * @param client identification of the client
1134 * @param message the actual message
1137 handle_get_zero_anonymity (void *cls, struct GNUNET_SERVER_Client *client,
1138 const struct GNUNET_MessageHeader *message)
1140 const struct GetZeroAnonymityMessage *msg =
1141 (const struct GetZeroAnonymityMessage *) message;
1142 enum GNUNET_BLOCK_Type type;
1144 type = (enum GNUNET_BLOCK_Type) ntohl (msg->type);
1145 if (type == GNUNET_BLOCK_TYPE_ANY)
1148 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1151 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Processing `%s' request\n",
1152 "GET_ZERO_ANONYMITY");
1153 GNUNET_STATISTICS_update (stats,
1155 ("# GET ZERO ANONYMITY requests received"), 1,
1157 GNUNET_SERVER_client_keep (client);
1158 plugin->api->get_zero_anonymity (plugin->api->cls,
1159 GNUNET_ntohll (msg->offset), type,
1160 &transmit_item, client);
1165 * Callback function that will cause the item that is passed
1166 * in to be deleted (by returning GNUNET_NO).
1169 remove_callback (void *cls, const struct GNUNET_HashCode * key, uint32_t size,
1170 const void *data, enum GNUNET_BLOCK_Type type,
1171 uint32_t priority, uint32_t anonymity,
1172 struct GNUNET_TIME_Absolute expiration, uint64_t uid)
1174 struct GNUNET_SERVER_Client *client = cls;
1178 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1179 "No further matches for `%s' request.\n", "REMOVE");
1180 transmit_status (client, GNUNET_NO, _("Content not found"));
1181 GNUNET_SERVER_client_drop (client);
1182 return GNUNET_OK; /* last item */
1184 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1185 "Item %llu matches `%s' request for key `%s' and type %u.\n",
1186 (unsigned long long) uid, "REMOVE", GNUNET_h2s (key), type);
1187 GNUNET_STATISTICS_update (stats,
1188 gettext_noop ("# bytes removed (explicit request)"),
1190 GNUNET_CONTAINER_bloomfilter_remove (filter, key);
1191 transmit_status (client, GNUNET_OK, NULL);
1192 GNUNET_SERVER_client_drop (client);
1198 * Handle REMOVE-message.
1200 * @param cls closure
1201 * @param client identification of the client
1202 * @param message the actual message
1205 handle_remove (void *cls, struct GNUNET_SERVER_Client *client,
1206 const struct GNUNET_MessageHeader *message)
1208 const struct DataMessage *dm = check_data (message);
1209 struct GNUNET_HashCode vhash;
1214 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1217 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1218 "Processing `%s' request for `%s' of type %u\n", "REMOVE",
1219 GNUNET_h2s (&dm->key), ntohl (dm->type));
1220 GNUNET_STATISTICS_update (stats, gettext_noop ("# REMOVE requests received"),
1222 GNUNET_SERVER_client_keep (client);
1223 GNUNET_CRYPTO_hash (&dm[1], ntohl (dm->size), &vhash);
1224 plugin->api->get_key (plugin->api->cls, 0, &dm->key, &vhash,
1225 (enum GNUNET_BLOCK_Type) ntohl (dm->type),
1226 &remove_callback, client);
1231 * Handle DROP-message.
1233 * @param cls closure
1234 * @param client identification of the client
1235 * @param message the actual message
1238 handle_drop (void *cls, struct GNUNET_SERVER_Client *client,
1239 const struct GNUNET_MessageHeader *message)
1241 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1242 "Processing `%s' request\n",
1244 do_drop = GNUNET_YES;
1245 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1250 * Function called by plugins to notify us about a
1251 * change in their disk utilization.
1253 * @param cls closure (NULL)
1254 * @param delta change in disk utilization,
1255 * 0 for "reset to empty"
1258 disk_utilization_change_cb (void *cls,
1261 if ((delta < 0) && (payload < -delta))
1263 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1264 _("Datastore payload must have been inaccurate (%lld < %lld). Recomputing it.\n"),
1265 (long long) payload,
1266 (long long) -delta);
1267 plugin->api->estimate_size (plugin->api->cls, &payload);
1268 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1269 _("New payload: %lld\n"),
1270 (long long) payload);
1276 if (last_sync >= MAX_STAT_SYNC_LAG)
1282 * Callback function to process statistic values.
1284 * @param cls closure (struct Plugin*)
1285 * @param subsystem name of subsystem that created the statistic
1286 * @param name the name of the datum
1287 * @param value the current value
1288 * @param is_persistent #GNUNET_YES if the value is persistent, #GNUNET_NO if not
1289 * @return #GNUNET_OK to continue, #GNUNET_SYSERR to abort iteration
1292 process_stat_in (void *cls,
1293 const char *subsystem,
1298 GNUNET_assert (GNUNET_NO == stats_worked);
1299 stats_worked = GNUNET_YES;
1301 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1302 "Notification from statistics about existing payload (%llu), new payload is %llu\n",
1309 * Load the datastore plugin.
1311 static struct DatastorePlugin *
1314 struct DatastorePlugin *ret;
1317 ret = GNUNET_new (struct DatastorePlugin);
1319 ret->env.duc = &disk_utilization_change_cb;
1320 ret->env.cls = NULL;
1321 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1322 _("Loading `%s' datastore plugin\n"),
1324 GNUNET_asprintf (&libname,
1325 "libgnunet_plugin_datastore_%s",
1327 ret->short_name = GNUNET_strdup (plugin_name);
1328 ret->lib_name = libname;
1329 ret->api = GNUNET_PLUGIN_load (libname, &ret->env);
1330 if (NULL == ret->api)
1332 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1333 _("Failed to load datastore plugin for `%s'\n"),
1335 GNUNET_free (ret->short_name);
1336 GNUNET_free (libname);
1345 * Function called when the service shuts
1346 * down. Unloads our datastore plugin.
1348 * @param plug plugin to unload
1351 unload_plugin (struct DatastorePlugin *plug)
1353 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1354 "Datastore service is unloading plugin...\n");
1355 GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
1356 GNUNET_free (plug->lib_name);
1357 GNUNET_free (plug->short_name);
1362 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1363 {&handle_reserve, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_RESERVE,
1364 sizeof (struct ReserveMessage)},
1365 {&handle_release_reserve, NULL,
1366 GNUNET_MESSAGE_TYPE_DATASTORE_RELEASE_RESERVE,
1367 sizeof (struct ReleaseReserveMessage)},
1368 {&handle_put, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_PUT, 0},
1369 {&handle_update, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_UPDATE,
1370 sizeof (struct UpdateMessage)},
1371 {&handle_get, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_GET, 0},
1372 {&handle_get_replication, NULL,
1373 GNUNET_MESSAGE_TYPE_DATASTORE_GET_REPLICATION,
1374 sizeof (struct GNUNET_MessageHeader)},
1375 {&handle_get_zero_anonymity, NULL,
1376 GNUNET_MESSAGE_TYPE_DATASTORE_GET_ZERO_ANONYMITY,
1377 sizeof (struct GetZeroAnonymityMessage)},
1378 {&handle_remove, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_REMOVE, 0},
1379 {&handle_drop, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_DROP,
1380 sizeof (struct GNUNET_MessageHeader)},
1386 * Adds a given @a key to the bloomfilter in @a cls @a count times.
1388 * @param cls the bloomfilter
1389 * @param key key to add
1390 * @param count number of times to add key
1393 add_key_to_bloomfilter (void *cls,
1394 const struct GNUNET_HashCode *key,
1397 struct GNUNET_CONTAINER_BloomFilter *bf = cls;
1401 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1402 _("Bloomfilter construction complete.\n"));
1403 GNUNET_SERVER_add_handlers (server, handlers);
1404 GNUNET_SERVER_resume (server);
1406 = GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE,
1413 GNUNET_CONTAINER_bloomfilter_add (bf, key);
1418 * We finished receiving the statistic. Initialize the plugin; if
1419 * loading the statistic failed, run the estimator.
1422 * @param success #GNUNET_NO if we failed to read the stat
1425 process_stat_done (void *cls, int success)
1429 plugin = load_plugin ();
1432 GNUNET_CONTAINER_bloomfilter_free (filter);
1436 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
1441 if (GNUNET_NO == stats_worked)
1443 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1444 "Failed to obtain value from statistics service, recomputing it\n");
1445 plugin->api->estimate_size (plugin->api->cls, &payload);
1447 if (GNUNET_YES == refresh_bf)
1449 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1450 _("Rebuilding bloomfilter. Please be patient.\n"));
1451 if (NULL != plugin->api->get_keys)
1453 plugin->api->get_keys (plugin->api->cls,
1454 &add_key_to_bloomfilter,
1459 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1460 _("Plugin does not support get_keys function. Please fix!\n"));
1462 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1463 _("Bloomfilter construction complete.\n"));
1466 GNUNET_SERVER_add_handlers (server, handlers);
1467 GNUNET_SERVER_resume (server);
1469 = GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE,
1476 * Task run during shutdown.
1479 cleaning_task (void *cls,
1480 const struct GNUNET_SCHEDULER_TaskContext *tc)
1482 struct TransmitCallbackContext *tcc;
1484 cleaning_done = GNUNET_YES;
1485 while (NULL != (tcc = tcc_head))
1487 GNUNET_CONTAINER_DLL_remove (tcc_head, tcc_tail, tcc);
1488 if (tcc->th != NULL)
1490 GNUNET_SERVER_notify_transmit_ready_cancel (tcc->th);
1491 GNUNET_SERVER_client_drop (tcc->client);
1493 GNUNET_free (tcc->msg);
1496 if (NULL != expired_kill_task)
1498 GNUNET_SCHEDULER_cancel (expired_kill_task);
1499 expired_kill_task = NULL;
1501 if (GNUNET_YES == do_drop)
1502 plugin->api->drop (plugin->api->cls);
1505 unload_plugin (plugin);
1510 GNUNET_CONTAINER_bloomfilter_free (filter);
1513 if (NULL != stat_get)
1515 GNUNET_STATISTICS_get_cancel (stat_get);
1518 GNUNET_free_non_null (plugin_name);
1524 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
1527 GNUNET_free (quota_stat_name);
1528 quota_stat_name = NULL;
1533 * Function that removes all active reservations made
1534 * by the given client and releases the space for other
1537 * @param cls closure
1538 * @param client identification of the client
1541 cleanup_reservations (void *cls,
1542 struct GNUNET_SERVER_Client *client)
1544 struct ReservationList *pos;
1545 struct ReservationList *prev;
1546 struct ReservationList *next;
1555 if (pos->client == client)
1558 reservations = next;
1561 reserved -= pos->amount + pos->entries * GNUNET_DATASTORE_ENTRY_OVERHEAD;
1570 GNUNET_STATISTICS_set (stats, gettext_noop ("# reserved"), reserved,
1576 * Process datastore requests.
1578 * @param cls closure
1579 * @param serv the initialized server
1580 * @param c configuration to use
1584 struct GNUNET_SERVER_Handle *serv,
1585 const struct GNUNET_CONFIGURATION_Handle *c)
1589 unsigned int bf_size;
1594 GNUNET_CONFIGURATION_get_value_string (cfg, "DATASTORE", "DATABASE",
1597 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1598 _("No `%s' specified for `%s' in configuration!\n"), "DATABASE",
1602 GNUNET_asprintf ("a_stat_name,
1603 _("# bytes used in file-sharing datastore `%s'"),
1606 GNUNET_CONFIGURATION_get_value_size (cfg, "DATASTORE", "QUOTA", "a))
1608 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1609 _("No `%s' specified for `%s' in configuration!\n"), "QUOTA",
1613 stats = GNUNET_STATISTICS_create ("datastore", cfg);
1614 GNUNET_STATISTICS_set (stats, gettext_noop ("# quota"), quota, GNUNET_NO);
1615 cache_size = quota / 8; /* Or should we make this an option? */
1616 GNUNET_STATISTICS_set (stats, gettext_noop ("# cache size"), cache_size,
1618 if (quota / (32 * 1024LL) > (1 << 31))
1619 bf_size = (1 << 31); /* absolute limit: ~2 GB, beyond that BF just won't help anyway */
1621 bf_size = quota / (32 * 1024LL); /* 8 bit per entry, 1 bit per 32 kb in DB */
1624 GNUNET_CONFIGURATION_get_value_filename (cfg, "DATASTORE", "BLOOMFILTER",
1626 (GNUNET_OK != GNUNET_DISK_directory_create_for_file (fn)))
1628 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1629 _("Could not use specified filename `%s' for bloomfilter.\n"),
1630 NULL != fn ? fn : "");
1631 GNUNET_free_non_null (fn);
1636 GNUNET_asprintf (&pfn, "%s.%s", fn, plugin_name);
1637 if (GNUNET_YES == GNUNET_DISK_file_test (pfn))
1639 filter = GNUNET_CONTAINER_bloomfilter_load (pfn, bf_size, 5); /* approx. 3% false positives at max use */
1642 /* file exists but not valid, remove and try again, but refresh */
1643 if (0 != UNLINK (pfn))
1645 /* failed to remove, run without file */
1646 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1647 _("Failed to remove bogus bloomfilter file `%s'\n"),
1651 filter = GNUNET_CONTAINER_bloomfilter_load (NULL, bf_size, 5); /* approx. 3% false positives at max use */
1652 refresh_bf = GNUNET_YES;
1656 /* try again after remove */
1657 filter = GNUNET_CONTAINER_bloomfilter_load (pfn, bf_size, 5); /* approx. 3% false positives at max use */
1658 refresh_bf = GNUNET_YES;
1661 /* failed yet again, give up on using file */
1662 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1663 _("Failed to remove bogus bloomfilter file `%s'\n"),
1667 filter = GNUNET_CONTAINER_bloomfilter_init (NULL, bf_size, 5); /* approx. 3% false positives at max use */
1673 /* normal case: have an existing valid bf file, no need to refresh */
1674 refresh_bf = GNUNET_NO;
1679 filter = GNUNET_CONTAINER_bloomfilter_load (pfn, bf_size, 5); /* approx. 3% false positives at max use */
1680 refresh_bf = GNUNET_YES;
1686 filter = GNUNET_CONTAINER_bloomfilter_init (NULL, bf_size, 5); /* approx. 3% false positives at max use */
1687 refresh_bf = GNUNET_YES;
1689 GNUNET_free_non_null (fn);
1692 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1693 _("Failed to initialize bloomfilter.\n"));
1696 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
1701 GNUNET_SERVER_suspend (server);
1703 GNUNET_STATISTICS_get (stats,
1706 GNUNET_TIME_UNIT_SECONDS,
1710 if (NULL == stat_get)
1711 process_stat_done (NULL, GNUNET_SYSERR);
1712 GNUNET_SERVER_disconnect_notify (server,
1713 &cleanup_reservations,
1715 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1722 * The main function for the datastore service.
1724 * @param argc number of arguments from the command line
1725 * @param argv command line arguments
1726 * @return 0 ok, 1 on error
1736 GNUNET_SERVICE_run (argc, argv, "datastore",
1737 GNUNET_SERVICE_OPTION_NONE,
1738 &run, NULL)) ? 0 : 1;
1743 /* end of gnunet-service-datastore.c */