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., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, 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,
231 GNUNET_STATISTICS_set (stats,
232 "# utilization by current datastore",
240 * Context for transmitting replies to clients.
242 struct TransmitCallbackContext
246 * We keep these in a doubly-linked list (for cleanup).
248 struct TransmitCallbackContext *next;
251 * We keep these in a doubly-linked list (for cleanup).
253 struct TransmitCallbackContext *prev;
256 * The message that we're asked to transmit.
258 struct GNUNET_MessageHeader *msg;
261 * Handle for the transmission request.
263 struct GNUNET_SERVER_TransmitHandle *th;
266 * Client that we are transmitting to.
268 struct GNUNET_SERVER_Client *client;
274 * Head of the doubly-linked list (for cleanup).
276 static struct TransmitCallbackContext *tcc_head;
279 * Tail of the doubly-linked list (for cleanup).
281 static struct TransmitCallbackContext *tcc_tail;
284 * Have we already cleaned up the TCCs and are hence no longer
285 * willing (or able) to transmit anything to anyone?
287 static int cleaning_done;
290 * Handle for pending get request.
292 static struct GNUNET_STATISTICS_GetHandle *stat_get;
295 * Handle to our server.
297 static struct GNUNET_SERVER_Handle *server;
300 * Task that is used to remove expired entries from
301 * the datastore. This task will schedule itself
302 * again automatically to always delete all expired
305 * @param cls not used
306 * @param tc task context
309 delete_expired (void *cls,
310 const struct GNUNET_SCHEDULER_TaskContext *tc);
314 * Iterate over the expired items stored in the datastore.
315 * Delete all expired items; once we have processed all
316 * expired items, re-schedule the "delete_expired" task.
318 * @param cls not used
319 * @param key key for the content
320 * @param size number of bytes in data
321 * @param data content stored
322 * @param type type of the content
323 * @param priority priority of the content
324 * @param anonymity anonymity-level for the content
325 * @param expiration expiration time for the content
326 * @param uid unique identifier for the datum;
327 * maybe 0 if no unique identifier is available
329 * @return #GNUNET_SYSERR to abort the iteration, #GNUNET_OK to continue
330 * (continue on call to "next", of course),
331 * #GNUNET_NO to delete the item and continue (if supported)
334 expired_processor (void *cls,
335 const struct GNUNET_HashCode *key,
338 enum GNUNET_BLOCK_Type type,
341 struct GNUNET_TIME_Absolute expiration,
344 struct GNUNET_TIME_Absolute now;
349 GNUNET_SCHEDULER_add_delayed_with_priority (MAX_EXPIRE_DELAY,
350 GNUNET_SCHEDULER_PRIORITY_IDLE,
351 &delete_expired, NULL);
352 return GNUNET_SYSERR;
354 now = GNUNET_TIME_absolute_get ();
355 if (expiration.abs_value_us > now.abs_value_us)
357 /* finished processing */
359 GNUNET_SCHEDULER_add_delayed_with_priority (MAX_EXPIRE_DELAY,
360 GNUNET_SCHEDULER_PRIORITY_IDLE,
361 &delete_expired, NULL);
362 return GNUNET_SYSERR;
364 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
365 "Deleting content `%s' of type %u that expired %s ago\n",
366 GNUNET_h2s (key), type,
367 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_difference (expiration,
370 min_expiration = now;
371 GNUNET_STATISTICS_update (stats,
372 gettext_noop ("# bytes expired"),
375 GNUNET_CONTAINER_bloomfilter_remove (filter, key);
377 GNUNET_SCHEDULER_add_delayed_with_priority (MIN_EXPIRE_DELAY,
378 GNUNET_SCHEDULER_PRIORITY_IDLE,
379 &delete_expired, NULL);
385 * Task that is used to remove expired entries from
386 * the datastore. This task will schedule itself
387 * again automatically to always delete all expired
390 * @param cls not used
391 * @param tc task context
394 delete_expired (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
396 expired_kill_task = NULL;
397 plugin->api->get_expiration (plugin->api->cls, &expired_processor, NULL);
402 * An iterator over a set of items stored in the datastore
403 * that deletes until we're happy with respect to our quota.
406 * @param key key for the content
407 * @param size number of bytes in data
408 * @param data content stored
409 * @param type type of the content
410 * @param priority priority of the content
411 * @param anonymity anonymity-level for the content
412 * @param expiration expiration time for the content
413 * @param uid unique identifier for the datum;
414 * maybe 0 if no unique identifier is available
416 * @return GNUNET_SYSERR to abort the iteration, GNUNET_OK to continue
417 * (continue on call to "next", of course),
418 * GNUNET_NO to delete the item and continue (if supported)
421 quota_processor (void *cls, const struct GNUNET_HashCode * key, uint32_t size,
422 const void *data, enum GNUNET_BLOCK_Type type,
423 uint32_t priority, uint32_t anonymity,
424 struct GNUNET_TIME_Absolute expiration, uint64_t uid)
426 unsigned long long *need = cls;
429 return GNUNET_SYSERR;
430 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
431 "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",
432 (unsigned long long) (size + GNUNET_DATASTORE_ENTRY_OVERHEAD),
433 (unsigned int) priority,
434 GNUNET_h2s (key), type,
435 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining (expiration),
438 if (size + GNUNET_DATASTORE_ENTRY_OVERHEAD > *need)
441 *need -= size + GNUNET_DATASTORE_ENTRY_OVERHEAD;
443 min_expiration = GNUNET_TIME_UNIT_FOREVER_ABS;
445 min_expiration = expiration;
446 GNUNET_STATISTICS_update (stats,
447 gettext_noop ("# bytes purged (low-priority)"),
449 GNUNET_CONTAINER_bloomfilter_remove (filter, key);
455 * Manage available disk space by running tasks
456 * that will discard content if necessary. This
457 * function will be run whenever a request for
458 * "need" bytes of storage could only be satisfied
459 * by eating into the "cache" (and we want our cache
462 * @param need number of bytes of content that were
463 * placed into the "cache" (and hence the
464 * number of bytes that should be removed).
467 manage_space (unsigned long long need)
469 unsigned long long last;
471 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
472 "Asked to free up %llu bytes of cache space\n", need);
474 while ((need > 0) && (last != need))
477 plugin->api->get_expiration (plugin->api->cls, "a_processor, &need);
483 * Function called to notify a client about the socket
484 * begin ready to queue more data. "buf" will be
485 * NULL and "size" zero if the socket was closed for
486 * writing in the meantime.
489 * @param size number of bytes available in buf
490 * @param buf where the callee should write the message
491 * @return number of bytes written to buf
494 transmit_callback (void *cls, size_t size, void *buf)
496 struct TransmitCallbackContext *tcc = cls;
500 GNUNET_CONTAINER_DLL_remove (tcc_head, tcc_tail, tcc);
501 msize = ntohs (tcc->msg->size);
504 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
505 _("Transmission to client failed!\n"));
506 GNUNET_SERVER_receive_done (tcc->client, GNUNET_SYSERR);
507 GNUNET_SERVER_client_drop (tcc->client);
508 GNUNET_free (tcc->msg);
512 GNUNET_assert (size >= msize);
513 memcpy (buf, tcc->msg, msize);
514 GNUNET_SERVER_receive_done (tcc->client, GNUNET_OK);
515 GNUNET_SERVER_client_drop (tcc->client);
516 GNUNET_free (tcc->msg);
523 * Transmit the given message to the client.
525 * @param client target of the message
526 * @param msg message to transmit, will be freed!
529 transmit (struct GNUNET_SERVER_Client *client, struct GNUNET_MessageHeader *msg)
531 struct TransmitCallbackContext *tcc;
533 if (GNUNET_YES == cleaning_done)
535 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
536 _("Shutdown in progress, aborting transmission.\n"));
537 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
541 tcc = GNUNET_new (struct TransmitCallbackContext);
543 tcc->client = client;
546 GNUNET_SERVER_notify_transmit_ready (client, ntohs (msg->size),
547 GNUNET_TIME_UNIT_FOREVER_REL,
548 &transmit_callback, tcc)))
551 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
556 GNUNET_SERVER_client_keep (client);
557 GNUNET_CONTAINER_DLL_insert (tcc_head, tcc_tail, tcc);
562 * Transmit a status code to the client.
564 * @param client receiver of the response
565 * @param code status code
566 * @param msg optional error message (can be NULL)
569 transmit_status (struct GNUNET_SERVER_Client *client, int code, const char *msg)
571 struct StatusMessage *sm;
574 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
575 "Transmitting `%s' message with value %d and message `%s'\n",
576 "STATUS", code, msg != NULL ? msg : "(none)");
577 slen = (msg == NULL) ? 0 : strlen (msg) + 1;
578 sm = GNUNET_malloc (sizeof (struct StatusMessage) + slen);
579 sm->header.size = htons (sizeof (struct StatusMessage) + slen);
580 sm->header.type = htons (GNUNET_MESSAGE_TYPE_DATASTORE_STATUS);
581 sm->status = htonl (code);
582 sm->min_expiration = GNUNET_TIME_absolute_hton (min_expiration);
584 memcpy (&sm[1], msg, slen);
585 transmit (client, &sm->header);
590 * Function that will transmit the given datastore entry
593 * @param cls closure, pointer to the client (of type GNUNET_SERVER_Client).
594 * @param key key for the content
595 * @param size number of bytes in data
596 * @param data content stored
597 * @param type type of the content
598 * @param priority priority of the content
599 * @param anonymity anonymity-level for the content
600 * @param expiration expiration time for the content
601 * @param uid unique identifier for the datum;
602 * maybe 0 if no unique identifier is available
604 * @return GNUNET_SYSERR to abort the iteration, GNUNET_OK to continue,
605 * GNUNET_NO to delete the item and continue (if supported)
608 transmit_item (void *cls, const struct GNUNET_HashCode * key, uint32_t size,
609 const void *data, enum GNUNET_BLOCK_Type type, uint32_t priority,
610 uint32_t anonymity, struct GNUNET_TIME_Absolute expiration,
613 struct GNUNET_SERVER_Client *client = cls;
614 struct GNUNET_MessageHeader *end;
615 struct DataMessage *dm;
619 /* transmit 'DATA_END' */
620 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transmitting `%s' message\n",
622 end = GNUNET_new (struct GNUNET_MessageHeader);
623 end->size = htons (sizeof (struct GNUNET_MessageHeader));
624 end->type = htons (GNUNET_MESSAGE_TYPE_DATASTORE_DATA_END);
625 transmit (client, end);
626 GNUNET_SERVER_client_drop (client);
629 GNUNET_assert (sizeof (struct DataMessage) + size <
630 GNUNET_SERVER_MAX_MESSAGE_SIZE);
631 dm = GNUNET_malloc (sizeof (struct DataMessage) + size);
632 dm->header.size = htons (sizeof (struct DataMessage) + size);
633 dm->header.type = htons (GNUNET_MESSAGE_TYPE_DATASTORE_DATA);
635 dm->size = htonl (size);
636 dm->type = htonl (type);
637 dm->priority = htonl (priority);
638 dm->anonymity = htonl (anonymity);
639 dm->replication = htonl (0);
640 dm->reserved = htonl (0);
641 dm->expiration = GNUNET_TIME_absolute_hton (expiration);
642 dm->uid = GNUNET_htonll (uid);
644 memcpy (&dm[1], data, size);
645 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
646 "Transmitting `%s' message for `%s' of type %u with expiration %s (in: %s)\n",
647 "DATA", GNUNET_h2s (key), type,
648 GNUNET_STRINGS_absolute_time_to_string (expiration),
649 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_remaining (expiration),
651 GNUNET_STATISTICS_update (stats,
652 gettext_noop ("# results found"),
655 transmit (client, &dm->header);
656 GNUNET_SERVER_client_drop (client);
662 * Handle RESERVE-message.
665 * @param client identification of the client
666 * @param message the actual message
669 handle_reserve (void *cls, struct GNUNET_SERVER_Client *client,
670 const struct GNUNET_MessageHeader *message)
673 * Static counter to produce reservation identifiers.
675 static int reservation_gen;
677 const struct ReserveMessage *msg = (const struct ReserveMessage *) message;
678 struct ReservationList *e;
679 unsigned long long used;
680 unsigned long long req;
684 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Processing `%s' request\n", "RESERVE");
685 amount = GNUNET_ntohll (msg->amount);
686 entries = ntohl (msg->entries);
687 used = payload + reserved;
689 amount + ((unsigned long long) GNUNET_DATASTORE_ENTRY_OVERHEAD) * entries;
690 if (used + req > quota)
693 used = quota; /* cheat a bit for error message (to avoid negative numbers) */
694 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
696 ("Insufficient space (%llu bytes are available) to satisfy `%s' request for %llu bytes\n"),
697 quota - used, "RESERVE", req);
698 if (cache_size < req)
700 /* TODO: document this in the FAQ; essentially, if this
701 * message happens, the insertion request could be blocked
702 * by less-important content from migration because it is
703 * larger than 1/8th of the overall available space, and
704 * we only reserve 1/8th for "fresh" insertions */
705 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
707 ("The requested amount (%llu bytes) is larger than the cache size (%llu bytes)\n"),
709 transmit_status (client, 0,
711 ("Insufficient space to satisfy request and "
712 "requested amount is larger than cache size"));
716 transmit_status (client, 0,
717 gettext_noop ("Insufficient space to satisfy request"));
722 GNUNET_STATISTICS_set (stats,
723 gettext_noop ("# reserved"),
726 e = GNUNET_new (struct ReservationList);
727 e->next = reservations;
731 e->entries = entries;
732 e->rid = ++reservation_gen;
733 if (reservation_gen < 0)
734 reservation_gen = 0; /* wrap around */
735 transmit_status (client, e->rid, NULL);
740 * Handle RELEASE_RESERVE-message.
743 * @param client identification of the client
744 * @param message the actual message
747 handle_release_reserve (void *cls,
748 struct GNUNET_SERVER_Client *client,
749 const struct GNUNET_MessageHeader *message)
751 const struct ReleaseReserveMessage *msg =
752 (const struct ReleaseReserveMessage *) message;
753 struct ReservationList *pos;
754 struct ReservationList *prev;
755 struct ReservationList *next;
756 int rid = ntohl (msg->rid);
757 unsigned long long rem;
759 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
760 "Processing `%s' request\n",
764 while (NULL != (pos = next))
775 ((unsigned long long) GNUNET_DATASTORE_ENTRY_OVERHEAD) * pos->entries;
776 GNUNET_assert (reserved >= rem);
778 GNUNET_STATISTICS_set (stats,
779 gettext_noop ("# reserved"),
782 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
783 "Returning %llu remaining reserved bytes to storage pool\n",
786 transmit_status (client, GNUNET_OK, NULL);
792 transmit_status (client, GNUNET_SYSERR,
793 gettext_noop ("Could not find matching reservation"));
798 * Check that the given message is a valid data message.
800 * @return NULL if the message is not well-formed, otherwise the message
802 static const struct DataMessage *
803 check_data (const struct GNUNET_MessageHeader *message)
807 const struct DataMessage *dm;
809 size = ntohs (message->size);
810 if (size < sizeof (struct DataMessage))
815 dm = (const struct DataMessage *) message;
816 dsize = ntohl (dm->size);
817 if (size != dsize + sizeof (struct DataMessage))
827 * Context for a PUT request used to see if the content is
833 * Client to notify on completion.
835 struct GNUNET_SERVER_Client *client;
837 #if ! HAVE_UNALIGNED_64_ACCESS
841 /* followed by the 'struct DataMessage' */
849 * @param key key for the item stored
850 * @param size size of the item stored
851 * @param status #GNUNET_OK or #GNUNET_SYSERROR
852 * @param msg error message on error
855 put_continuation (void *cls,
856 const struct GNUNET_HashCode *key,
861 struct GNUNET_SERVER_Client *client = cls;
863 if (GNUNET_OK == status)
865 GNUNET_STATISTICS_update (stats,
866 gettext_noop ("# bytes stored"),
869 GNUNET_CONTAINER_bloomfilter_add (filter, key);
870 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
871 "Successfully stored %u bytes under key `%s'\n",
872 size, GNUNET_h2s (key));
874 transmit_status (client, status, msg);
875 GNUNET_SERVER_client_drop (client);
876 if (quota - reserved - cache_size < payload)
878 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
879 _("Need %llu bytes more space (%llu allowed, using %llu)\n"),
880 (unsigned long long) size + GNUNET_DATASTORE_ENTRY_OVERHEAD,
881 (unsigned long long) (quota - reserved - cache_size),
882 (unsigned long long) payload);
883 manage_space (size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
889 * Actually put the data message.
891 * @param client sender of the message
892 * @param dm message with the data to store
895 execute_put (struct GNUNET_SERVER_Client *client,
896 const struct DataMessage *dm)
898 GNUNET_SERVER_client_keep (client);
899 plugin->api->put (plugin->api->cls, &dm->key, ntohl (dm->size), &dm[1],
900 ntohl (dm->type), ntohl (dm->priority),
901 ntohl (dm->anonymity), ntohl (dm->replication),
902 GNUNET_TIME_absolute_ntoh (dm->expiration),
903 &put_continuation, client);
908 check_present_continuation (void *cls,
912 struct GNUNET_SERVER_Client *client = cls;
914 transmit_status (client, GNUNET_NO, NULL);
915 GNUNET_SERVER_client_drop (client);
920 * Function that will check if the given datastore entry
921 * matches the put and if none match executes the put.
923 * @param cls closure, pointer to the client (of type `struct PutContext`).
924 * @param key key for the content
925 * @param size number of bytes in data
926 * @param data content stored
927 * @param type type of the content
928 * @param priority priority of the content
929 * @param anonymity anonymity-level for the content
930 * @param expiration expiration time for the content
931 * @param uid unique identifier for the datum;
932 * maybe 0 if no unique identifier is available
933 * @return #GNUNET_OK usually
934 * #GNUNET_NO to delete the item
937 check_present (void *cls,
938 const struct GNUNET_HashCode *key,
941 enum GNUNET_BLOCK_Type type,
944 struct GNUNET_TIME_Absolute expiration,
947 struct PutContext *pc = cls;
948 const struct DataMessage *dm;
950 dm = (const struct DataMessage *) &pc[1];
953 execute_put (pc->client, dm);
954 GNUNET_SERVER_client_drop (pc->client);
958 if ((GNUNET_BLOCK_TYPE_FS_DBLOCK == type) ||
959 (GNUNET_BLOCK_TYPE_FS_IBLOCK == type) || ((size == ntohl (dm->size)) &&
961 memcmp (&dm[1], data, size))))
963 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
964 "Result already present in datastore\n");
965 /* FIXME: change API to allow increasing 'replication' counter */
966 if ((ntohl (dm->priority) > 0) ||
967 (GNUNET_TIME_absolute_ntoh (dm->expiration).abs_value_us >
968 expiration.abs_value_us))
969 plugin->api->update (plugin->api->cls,
971 (int32_t) ntohl (dm->priority),
972 GNUNET_TIME_absolute_ntoh (dm->expiration),
973 &check_present_continuation,
977 transmit_status (pc->client, GNUNET_NO, NULL);
978 GNUNET_SERVER_client_drop (pc->client);
984 execute_put (pc->client, dm);
985 GNUNET_SERVER_client_drop (pc->client);
993 * Handle PUT-message.
996 * @param client identification of the client
997 * @param message the actual message
1000 handle_put (void *cls, struct GNUNET_SERVER_Client *client,
1001 const struct GNUNET_MessageHeader *message)
1003 const struct DataMessage *dm = check_data (message);
1005 struct ReservationList *pos;
1006 struct PutContext *pc;
1007 struct GNUNET_HashCode vhash;
1010 if ((dm == NULL) || (ntohl (dm->type) == 0))
1013 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1016 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1017 "Processing `%s' request for `%s' of type %u\n", "PUT",
1018 GNUNET_h2s (&dm->key), ntohl (dm->type));
1019 rid = ntohl (dm->rid);
1020 size = ntohl (dm->size);
1024 while ((NULL != pos) && (rid != pos->rid))
1026 GNUNET_break (pos != NULL);
1029 GNUNET_break (pos->entries > 0);
1030 GNUNET_break (pos->amount >= size);
1032 pos->amount -= size;
1033 reserved -= (size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
1034 GNUNET_STATISTICS_set (stats,
1035 gettext_noop ("# reserved"),
1040 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (filter, &dm->key))
1042 GNUNET_CRYPTO_hash (&dm[1], size, &vhash);
1043 pc = GNUNET_malloc (sizeof (struct PutContext) + size +
1044 sizeof (struct DataMessage));
1045 pc->client = client;
1046 GNUNET_SERVER_client_keep (client);
1047 memcpy (&pc[1], dm, size + sizeof (struct DataMessage));
1048 plugin->api->get_key (plugin->api->cls,
1057 execute_put (client, dm);
1062 * Handle GET-message.
1064 * @param cls closure
1065 * @param client identification of the client
1066 * @param message the actual message
1069 handle_get (void *cls, struct GNUNET_SERVER_Client *client,
1070 const struct GNUNET_MessageHeader *message)
1072 const struct GetMessage *msg;
1075 size = ntohs (message->size);
1076 if ((size != sizeof (struct GetMessage)) &&
1077 (size != sizeof (struct GetMessage) - sizeof (struct GNUNET_HashCode)))
1080 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1083 msg = (const struct GetMessage *) message;
1084 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1085 "Processing `%s' request for `%s' of type %u\n", "GET",
1086 GNUNET_h2s (&msg->key), ntohl (msg->type));
1087 GNUNET_STATISTICS_update (stats,
1088 gettext_noop ("# GET requests received"),
1091 GNUNET_SERVER_client_keep (client);
1092 if ((size == sizeof (struct GetMessage)) &&
1093 (GNUNET_YES != GNUNET_CONTAINER_bloomfilter_test (filter, &msg->key)))
1095 /* don't bother database... */
1096 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1097 "Empty result set for `%s' request for `%s' (bloomfilter).\n",
1098 "GET", GNUNET_h2s (&msg->key));
1099 GNUNET_STATISTICS_update (stats,
1101 ("# requests filtered by bloomfilter"),
1104 transmit_item (client, NULL, 0, NULL, 0, 0, 0, GNUNET_TIME_UNIT_ZERO_ABS,
1108 plugin->api->get_key (plugin->api->cls, GNUNET_ntohll (msg->offset),
1110 sizeof (struct GetMessage)) ? &msg->key : NULL), NULL,
1111 ntohl (msg->type), &transmit_item, client);
1116 update_continuation (void *cls,
1120 struct GNUNET_SERVER_Client *client = cls;
1122 transmit_status (client, status, msg);
1123 GNUNET_SERVER_client_drop (client);
1128 * Handle UPDATE-message.
1130 * @param cls closure
1131 * @param client identification of the client
1132 * @param message the actual message
1135 handle_update (void *cls, struct GNUNET_SERVER_Client *client,
1136 const struct GNUNET_MessageHeader *message)
1138 const struct UpdateMessage *msg;
1140 GNUNET_STATISTICS_update (stats,
1141 gettext_noop ("# UPDATE requests received"),
1144 msg = (const struct UpdateMessage *) message;
1145 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Processing `%s' request for %llu\n",
1146 "UPDATE", (unsigned long long) GNUNET_ntohll (msg->uid));
1147 GNUNET_SERVER_client_keep (client);
1148 plugin->api->update (plugin->api->cls, GNUNET_ntohll (msg->uid),
1149 (int32_t) ntohl (msg->priority),
1150 GNUNET_TIME_absolute_ntoh (msg->expiration),
1151 update_continuation, client);
1156 * Handle GET_REPLICATION-message.
1158 * @param cls closure
1159 * @param client identification of the client
1160 * @param message the actual message
1163 handle_get_replication (void *cls, struct GNUNET_SERVER_Client *client,
1164 const struct GNUNET_MessageHeader *message)
1166 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1167 "Processing `%s' request\n",
1169 GNUNET_STATISTICS_update (stats,
1170 gettext_noop ("# GET REPLICATION requests received"),
1173 GNUNET_SERVER_client_keep (client);
1174 plugin->api->get_replication (plugin->api->cls, &transmit_item, client);
1179 * Handle GET_ZERO_ANONYMITY-message.
1181 * @param cls closure
1182 * @param client identification of the client
1183 * @param message the actual message
1186 handle_get_zero_anonymity (void *cls, struct GNUNET_SERVER_Client *client,
1187 const struct GNUNET_MessageHeader *message)
1189 const struct GetZeroAnonymityMessage *msg =
1190 (const struct GetZeroAnonymityMessage *) message;
1191 enum GNUNET_BLOCK_Type type;
1193 type = (enum GNUNET_BLOCK_Type) ntohl (msg->type);
1194 if (type == GNUNET_BLOCK_TYPE_ANY)
1197 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1200 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1201 "Processing `%s' request\n",
1202 "GET_ZERO_ANONYMITY");
1203 GNUNET_STATISTICS_update (stats,
1204 gettext_noop ("# GET ZERO ANONYMITY requests received"),
1207 GNUNET_SERVER_client_keep (client);
1208 plugin->api->get_zero_anonymity (plugin->api->cls,
1209 GNUNET_ntohll (msg->offset), type,
1210 &transmit_item, client);
1215 * Callback function that will cause the item that is passed
1216 * in to be deleted (by returning GNUNET_NO).
1219 remove_callback (void *cls, const struct GNUNET_HashCode * key, uint32_t size,
1220 const void *data, enum GNUNET_BLOCK_Type type,
1221 uint32_t priority, uint32_t anonymity,
1222 struct GNUNET_TIME_Absolute expiration, uint64_t uid)
1224 struct GNUNET_SERVER_Client *client = cls;
1228 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1229 "No further matches for `%s' request.\n",
1231 transmit_status (client,
1233 _("Content not found"));
1234 GNUNET_SERVER_client_drop (client);
1235 return GNUNET_OK; /* last item */
1237 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1238 "Item %llu matches `%s' request for key `%s' and type %u.\n",
1239 (unsigned long long) uid,
1243 GNUNET_STATISTICS_update (stats,
1244 gettext_noop ("# bytes removed (explicit request)"),
1247 GNUNET_CONTAINER_bloomfilter_remove (filter, key);
1248 transmit_status (client, GNUNET_OK, NULL);
1249 GNUNET_SERVER_client_drop (client);
1255 * Handle REMOVE-message.
1257 * @param cls closure
1258 * @param client identification of the client
1259 * @param message the actual message
1262 handle_remove (void *cls, struct GNUNET_SERVER_Client *client,
1263 const struct GNUNET_MessageHeader *message)
1265 const struct DataMessage *dm = check_data (message);
1266 struct GNUNET_HashCode vhash;
1271 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1274 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1275 "Processing `%s' request for `%s' of type %u\n", "REMOVE",
1276 GNUNET_h2s (&dm->key), ntohl (dm->type));
1277 GNUNET_STATISTICS_update (stats, gettext_noop ("# REMOVE requests received"),
1279 GNUNET_SERVER_client_keep (client);
1280 GNUNET_CRYPTO_hash (&dm[1], ntohl (dm->size), &vhash);
1281 plugin->api->get_key (plugin->api->cls, 0, &dm->key, &vhash,
1282 (enum GNUNET_BLOCK_Type) ntohl (dm->type),
1283 &remove_callback, client);
1288 * Handle DROP-message.
1290 * @param cls closure
1291 * @param client identification of the client
1292 * @param message the actual message
1295 handle_drop (void *cls, struct GNUNET_SERVER_Client *client,
1296 const struct GNUNET_MessageHeader *message)
1298 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1299 "Processing `%s' request\n",
1301 do_drop = GNUNET_YES;
1302 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1307 * Function called by plugins to notify us about a
1308 * change in their disk utilization.
1310 * @param cls closure (NULL)
1311 * @param delta change in disk utilization,
1312 * 0 for "reset to empty"
1315 disk_utilization_change_cb (void *cls,
1318 if ((delta < 0) && (payload < -delta))
1320 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1321 _("Datastore payload must have been inaccurate (%lld < %lld). Recomputing it.\n"),
1322 (long long) payload,
1323 (long long) -delta);
1324 plugin->api->estimate_size (plugin->api->cls, &payload);
1325 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1326 _("New payload: %lld\n"),
1327 (long long) payload);
1333 if (last_sync >= MAX_STAT_SYNC_LAG)
1339 * Callback function to process statistic values.
1341 * @param cls closure (struct Plugin*)
1342 * @param subsystem name of subsystem that created the statistic
1343 * @param name the name of the datum
1344 * @param value the current value
1345 * @param is_persistent #GNUNET_YES if the value is persistent, #GNUNET_NO if not
1346 * @return #GNUNET_OK to continue, #GNUNET_SYSERR to abort iteration
1349 process_stat_in (void *cls,
1350 const char *subsystem,
1355 GNUNET_assert (GNUNET_NO == stats_worked);
1356 stats_worked = GNUNET_YES;
1358 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1359 "Notification from statistics about existing payload (%llu), new payload is %llu\n",
1366 * Load the datastore plugin.
1368 static struct DatastorePlugin *
1371 struct DatastorePlugin *ret;
1374 ret = GNUNET_new (struct DatastorePlugin);
1376 ret->env.duc = &disk_utilization_change_cb;
1377 ret->env.cls = NULL;
1378 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1379 _("Loading `%s' datastore plugin\n"),
1381 GNUNET_asprintf (&libname,
1382 "libgnunet_plugin_datastore_%s",
1384 ret->short_name = GNUNET_strdup (plugin_name);
1385 ret->lib_name = libname;
1386 ret->api = GNUNET_PLUGIN_load (libname, &ret->env);
1387 if (NULL == ret->api)
1389 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1390 _("Failed to load datastore plugin for `%s'\n"),
1392 GNUNET_free (ret->short_name);
1393 GNUNET_free (libname);
1402 * Function called when the service shuts
1403 * down. Unloads our datastore plugin.
1405 * @param plug plugin to unload
1408 unload_plugin (struct DatastorePlugin *plug)
1410 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1411 "Datastore service is unloading plugin...\n");
1412 GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
1413 GNUNET_free (plug->lib_name);
1414 GNUNET_free (plug->short_name);
1419 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1420 {&handle_reserve, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_RESERVE,
1421 sizeof (struct ReserveMessage)},
1422 {&handle_release_reserve, NULL,
1423 GNUNET_MESSAGE_TYPE_DATASTORE_RELEASE_RESERVE,
1424 sizeof (struct ReleaseReserveMessage)},
1425 {&handle_put, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_PUT, 0},
1426 {&handle_update, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_UPDATE,
1427 sizeof (struct UpdateMessage)},
1428 {&handle_get, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_GET, 0},
1429 {&handle_get_replication, NULL,
1430 GNUNET_MESSAGE_TYPE_DATASTORE_GET_REPLICATION,
1431 sizeof (struct GNUNET_MessageHeader)},
1432 {&handle_get_zero_anonymity, NULL,
1433 GNUNET_MESSAGE_TYPE_DATASTORE_GET_ZERO_ANONYMITY,
1434 sizeof (struct GetZeroAnonymityMessage)},
1435 {&handle_remove, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_REMOVE, 0},
1436 {&handle_drop, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_DROP,
1437 sizeof (struct GNUNET_MessageHeader)},
1443 * Adds a given @a key to the bloomfilter in @a cls @a count times.
1445 * @param cls the bloomfilter
1446 * @param key key to add
1447 * @param count number of times to add key
1450 add_key_to_bloomfilter (void *cls,
1451 const struct GNUNET_HashCode *key,
1454 struct GNUNET_CONTAINER_BloomFilter *bf = cls;
1458 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1459 _("Bloomfilter construction complete.\n"));
1460 GNUNET_SERVER_add_handlers (server, handlers);
1461 GNUNET_SERVER_resume (server);
1463 = GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE,
1470 GNUNET_CONTAINER_bloomfilter_add (bf, key);
1475 * We finished receiving the statistic. Initialize the plugin; if
1476 * loading the statistic failed, run the estimator.
1479 * @param success #GNUNET_NO if we failed to read the stat
1482 process_stat_done (void *cls,
1487 plugin = load_plugin ();
1490 GNUNET_CONTAINER_bloomfilter_free (filter);
1494 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
1499 if (GNUNET_NO == stats_worked)
1501 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1502 "Failed to obtain value from statistics service, recomputing it\n");
1503 plugin->api->estimate_size (plugin->api->cls,
1506 if (GNUNET_YES == refresh_bf)
1508 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1509 _("Rebuilding bloomfilter. Please be patient.\n"));
1510 if (NULL != plugin->api->get_keys)
1512 plugin->api->get_keys (plugin->api->cls,
1513 &add_key_to_bloomfilter,
1518 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1519 _("Plugin does not support get_keys function. Please fix!\n"));
1521 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1522 _("Bloomfilter construction complete.\n"));
1525 GNUNET_SERVER_add_handlers (server, handlers);
1526 GNUNET_SERVER_resume (server);
1528 = GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE,
1535 * Task run during shutdown.
1538 cleaning_task (void *cls,
1539 const struct GNUNET_SCHEDULER_TaskContext *tc)
1541 struct TransmitCallbackContext *tcc;
1543 cleaning_done = GNUNET_YES;
1544 while (NULL != (tcc = tcc_head))
1546 GNUNET_CONTAINER_DLL_remove (tcc_head, tcc_tail, tcc);
1547 if (tcc->th != NULL)
1549 GNUNET_SERVER_notify_transmit_ready_cancel (tcc->th);
1550 GNUNET_SERVER_client_drop (tcc->client);
1552 GNUNET_free (tcc->msg);
1555 if (NULL != expired_kill_task)
1557 GNUNET_SCHEDULER_cancel (expired_kill_task);
1558 expired_kill_task = NULL;
1560 if (GNUNET_YES == do_drop)
1561 plugin->api->drop (plugin->api->cls);
1564 unload_plugin (plugin);
1569 GNUNET_CONTAINER_bloomfilter_free (filter);
1572 if (NULL != stat_get)
1574 GNUNET_STATISTICS_get_cancel (stat_get);
1577 GNUNET_free_non_null (plugin_name);
1583 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
1586 GNUNET_free (quota_stat_name);
1587 quota_stat_name = NULL;
1592 * Function that removes all active reservations made
1593 * by the given client and releases the space for other
1596 * @param cls closure
1597 * @param client identification of the client
1600 cleanup_reservations (void *cls,
1601 struct GNUNET_SERVER_Client *client)
1603 struct ReservationList *pos;
1604 struct ReservationList *prev;
1605 struct ReservationList *next;
1614 if (pos->client == client)
1617 reservations = next;
1620 reserved -= pos->amount + pos->entries * GNUNET_DATASTORE_ENTRY_OVERHEAD;
1629 GNUNET_STATISTICS_set (stats,
1630 gettext_noop ("# reserved"),
1637 * Process datastore requests.
1639 * @param cls closure
1640 * @param serv the initialized server
1641 * @param c configuration to use
1645 struct GNUNET_SERVER_Handle *serv,
1646 const struct GNUNET_CONFIGURATION_Handle *c)
1650 unsigned int bf_size;
1655 GNUNET_CONFIGURATION_get_value_string (cfg,
1660 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1661 _("No `%s' specified for `%s' in configuration!\n"),
1666 GNUNET_asprintf ("a_stat_name,
1667 _("# bytes used in file-sharing datastore `%s'"),
1670 GNUNET_CONFIGURATION_get_value_size (cfg, "DATASTORE", "QUOTA", "a))
1672 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1673 _("No `%s' specified for `%s' in configuration!\n"),
1678 stats = GNUNET_STATISTICS_create ("datastore", cfg);
1679 GNUNET_STATISTICS_set (stats, gettext_noop ("# quota"), quota, GNUNET_NO);
1680 cache_size = quota / 8; /* Or should we make this an option? */
1681 GNUNET_STATISTICS_set (stats, gettext_noop ("# cache size"), cache_size,
1683 if (quota / (32 * 1024LL) > (1 << 31))
1684 bf_size = (1 << 31); /* absolute limit: ~2 GB, beyond that BF just won't help anyway */
1686 bf_size = quota / (32 * 1024LL); /* 8 bit per entry, 1 bit per 32 kb in DB */
1689 GNUNET_CONFIGURATION_get_value_filename (cfg,
1693 (GNUNET_OK != GNUNET_DISK_directory_create_for_file (fn)))
1695 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1696 _("Could not use specified filename `%s' for bloomfilter.\n"),
1697 NULL != fn ? fn : "");
1698 GNUNET_free_non_null (fn);
1703 GNUNET_asprintf (&pfn, "%s.%s", fn, plugin_name);
1704 if (GNUNET_YES == GNUNET_DISK_file_test (pfn))
1706 filter = GNUNET_CONTAINER_bloomfilter_load (pfn, bf_size, 5); /* approx. 3% false positives at max use */
1709 /* file exists but not valid, remove and try again, but refresh */
1710 if (0 != UNLINK (pfn))
1712 /* failed to remove, run without file */
1713 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1714 _("Failed to remove bogus bloomfilter file `%s'\n"),
1718 filter = GNUNET_CONTAINER_bloomfilter_load (NULL, bf_size, 5); /* approx. 3% false positives at max use */
1719 refresh_bf = GNUNET_YES;
1723 /* try again after remove */
1724 filter = GNUNET_CONTAINER_bloomfilter_load (pfn, bf_size, 5); /* approx. 3% false positives at max use */
1725 refresh_bf = GNUNET_YES;
1728 /* failed yet again, give up on using file */
1729 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1730 _("Failed to remove bogus bloomfilter file `%s'\n"),
1734 filter = GNUNET_CONTAINER_bloomfilter_init (NULL, bf_size, 5); /* approx. 3% false positives at max use */
1740 /* normal case: have an existing valid bf file, no need to refresh */
1741 refresh_bf = GNUNET_NO;
1746 filter = GNUNET_CONTAINER_bloomfilter_load (pfn, bf_size, 5); /* approx. 3% false positives at max use */
1747 refresh_bf = GNUNET_YES;
1753 filter = GNUNET_CONTAINER_bloomfilter_init (NULL, bf_size, 5); /* approx. 3% false positives at max use */
1754 refresh_bf = GNUNET_YES;
1756 GNUNET_free_non_null (fn);
1759 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1760 _("Failed to initialize bloomfilter.\n"));
1763 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
1768 GNUNET_SERVER_suspend (server);
1770 GNUNET_STATISTICS_get (stats,
1773 GNUNET_TIME_UNIT_SECONDS,
1777 if (NULL == stat_get)
1778 process_stat_done (NULL, GNUNET_SYSERR);
1779 GNUNET_SERVER_disconnect_notify (server,
1780 &cleanup_reservations,
1782 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1789 * The main function for the datastore service.
1791 * @param argc number of arguments from the command line
1792 * @param argv command line arguments
1793 * @return 0 ok, 1 on error
1803 GNUNET_SERVICE_run (argc, argv, "datastore",
1804 GNUNET_SERVICE_OPTION_NONE,
1805 &run, NULL)) ? 0 : 1;
1810 /* end of gnunet-service-datastore.c */