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 #define QUOTA_STAT_NAME gettext_noop ("# bytes used in file-sharing datastore")
55 * After how many payload-changing operations
56 * do we sync our statistics?
58 #define MAX_STAT_SYNC_LAG 50
62 * Our datastore plugin.
64 struct DatastorePlugin
68 * API of the transport as returned by the plugin's
69 * initialization function.
71 struct GNUNET_DATASTORE_PluginFunctions *api;
74 * Short name for the plugin (i.e. "sqlite").
79 * Name of the library (i.e. "gnunet_plugin_datastore_sqlite").
84 * Environment this transport service is using
87 struct GNUNET_DATASTORE_PluginEnvironment env;
93 * Linked list of active reservations.
95 struct ReservationList
99 * This is a linked list.
101 struct ReservationList *next;
104 * Client that made the reservation.
106 struct GNUNET_SERVER_Client *client;
109 * Number of bytes (still) reserved.
114 * Number of items (still) reserved.
119 * Reservation identifier.
128 * Our datastore plugin (NULL if not available).
130 static struct DatastorePlugin *plugin;
133 * Linked list of space reservations made by clients.
135 static struct ReservationList *reservations;
138 * Bloomfilter to quickly tell if we don't have the content.
140 static struct GNUNET_CONTAINER_BloomFilter *filter;
143 * How much space are we allowed to use?
145 static unsigned long long quota;
148 * Should the database be dropped on exit?
153 * How much space are we using for the cache? (space available for
154 * insertions that will be instantly reclaimed by discarding less
155 * important content --- or possibly whatever we just inserted into
158 static unsigned long long cache_size;
161 * How much space have we currently reserved?
163 static unsigned long long reserved;
166 * How much data are we currently storing
169 static unsigned long long payload;
172 * Number of updates that were made to the
173 * payload value since we last synchronized
174 * it with the statistics service.
176 static unsigned int lastSync;
179 * Did we get an answer from statistics?
181 static int stats_worked;
184 * Identity of the task that is used to delete
187 static GNUNET_SCHEDULER_TaskIdentifier expired_kill_task;
192 const struct GNUNET_CONFIGURATION_Handle *cfg;
196 * Handle for reporting statistics.
198 static struct GNUNET_STATISTICS_Handle *stats;
202 * Synchronize our utilization statistics with the
203 * statistics service.
208 GNUNET_STATISTICS_set (stats, QUOTA_STAT_NAME, payload, GNUNET_YES);
215 * Context for transmitting replies to clients.
217 struct TransmitCallbackContext
221 * We keep these in a doubly-linked list (for cleanup).
223 struct TransmitCallbackContext *next;
226 * We keep these in a doubly-linked list (for cleanup).
228 struct TransmitCallbackContext *prev;
231 * The message that we're asked to transmit.
233 struct GNUNET_MessageHeader *msg;
236 * Handle for the transmission request.
238 struct GNUNET_CONNECTION_TransmitHandle *th;
241 * Client that we are transmitting to.
243 struct GNUNET_SERVER_Client *client;
249 * Head of the doubly-linked list (for cleanup).
251 static struct TransmitCallbackContext *tcc_head;
254 * Tail of the doubly-linked list (for cleanup).
256 static struct TransmitCallbackContext *tcc_tail;
259 * Have we already cleaned up the TCCs and are hence no longer
260 * willing (or able) to transmit anything to anyone?
262 static int cleaning_done;
265 * Handle for pending get request.
267 static struct GNUNET_STATISTICS_GetHandle *stat_get;
271 * Task that is used to remove expired entries from
272 * the datastore. This task will schedule itself
273 * again automatically to always delete all expired
276 * @param cls not used
277 * @param tc task context
280 delete_expired (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
284 * Iterate over the expired items stored in the datastore.
285 * Delete all expired items; once we have processed all
286 * expired items, re-schedule the "delete_expired" task.
288 * @param cls not used
289 * @param key key for the content
290 * @param size number of bytes in data
291 * @param data content stored
292 * @param type type of the content
293 * @param priority priority of the content
294 * @param anonymity anonymity-level for the content
295 * @param expiration expiration time for the content
296 * @param uid unique identifier for the datum;
297 * maybe 0 if no unique identifier is available
299 * @return GNUNET_SYSERR to abort the iteration, GNUNET_OK to continue
300 * (continue on call to "next", of course),
301 * GNUNET_NO to delete the item and continue (if supported)
304 expired_processor (void *cls, const GNUNET_HashCode * key, uint32_t size,
305 const void *data, enum GNUNET_BLOCK_Type type,
306 uint32_t priority, uint32_t anonymity,
307 struct GNUNET_TIME_Absolute expiration, uint64_t uid)
309 struct GNUNET_TIME_Absolute now;
314 GNUNET_SCHEDULER_add_delayed (MAX_EXPIRE_DELAY, &delete_expired, NULL);
315 return GNUNET_SYSERR;
317 now = GNUNET_TIME_absolute_get ();
318 if (expiration.abs_value > now.abs_value)
320 /* finished processing */
322 GNUNET_SCHEDULER_add_delayed (MAX_EXPIRE_DELAY, &delete_expired, NULL);
323 return GNUNET_SYSERR;
326 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
327 "Deleting content `%s' of type %u that expired %llu ms ago\n",
328 GNUNET_h2s (key), type,
329 (unsigned long long) (now.abs_value - expiration.abs_value));
331 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes expired"), size,
333 GNUNET_CONTAINER_bloomfilter_remove (filter, key);
335 GNUNET_SCHEDULER_add_delayed (MIN_EXPIRE_DELAY, &delete_expired, NULL);
341 * Task that is used to remove expired entries from
342 * the datastore. This task will schedule itself
343 * again automatically to always delete all expired
346 * @param cls not used
347 * @param tc task context
350 delete_expired (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
352 expired_kill_task = GNUNET_SCHEDULER_NO_TASK;
353 plugin->api->get_expiration (plugin->api->cls, &expired_processor, NULL);
358 * An iterator over a set of items stored in the datastore
359 * that deletes until we're happy with respect to our quota.
362 * @param key key for the content
363 * @param size number of bytes in data
364 * @param data content stored
365 * @param type type of the content
366 * @param priority priority of the content
367 * @param anonymity anonymity-level for the content
368 * @param expiration expiration time for the content
369 * @param uid unique identifier for the datum;
370 * maybe 0 if no unique identifier is available
372 * @return GNUNET_SYSERR to abort the iteration, GNUNET_OK to continue
373 * (continue on call to "next", of course),
374 * GNUNET_NO to delete the item and continue (if supported)
377 quota_processor (void *cls, const GNUNET_HashCode * key, uint32_t size,
378 const void *data, enum GNUNET_BLOCK_Type type,
379 uint32_t priority, uint32_t anonymity,
380 struct GNUNET_TIME_Absolute expiration, uint64_t uid)
382 unsigned long long *need = cls;
385 return GNUNET_SYSERR;
387 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
388 "Deleting %llu bytes of low-priority content `%s' of type %u (still trying to free another %llu bytes)\n",
389 (unsigned long long) (size + GNUNET_DATASTORE_ENTRY_OVERHEAD),
390 GNUNET_h2s (key), type, *need);
392 if (size + GNUNET_DATASTORE_ENTRY_OVERHEAD > *need)
395 *need -= size + GNUNET_DATASTORE_ENTRY_OVERHEAD;
396 GNUNET_STATISTICS_update (stats,
397 gettext_noop ("# bytes purged (low-priority)"),
399 GNUNET_CONTAINER_bloomfilter_remove (filter, key);
405 * Manage available disk space by running tasks
406 * that will discard content if necessary. This
407 * function will be run whenever a request for
408 * "need" bytes of storage could only be satisfied
409 * by eating into the "cache" (and we want our cache
412 * @param need number of bytes of content that were
413 * placed into the "cache" (and hence the
414 * number of bytes that should be removed).
417 manage_space (unsigned long long need)
419 unsigned long long last;
422 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
423 "Asked to free up %llu bytes of cache space\n", need);
426 while ((need > 0) && (last != need))
429 plugin->api->get_expiration (plugin->api->cls, "a_processor, &need);
435 * Function called to notify a client about the socket
436 * begin ready to queue more data. "buf" will be
437 * NULL and "size" zero if the socket was closed for
438 * writing in the meantime.
441 * @param size number of bytes available in buf
442 * @param buf where the callee should write the message
443 * @return number of bytes written to buf
446 transmit_callback (void *cls, size_t size, void *buf)
448 struct TransmitCallbackContext *tcc = cls;
452 GNUNET_CONTAINER_DLL_remove (tcc_head, tcc_tail, tcc);
453 msize = ntohs (tcc->msg->size);
456 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
457 _("Transmission to client failed!\n"));
458 GNUNET_SERVER_receive_done (tcc->client, GNUNET_SYSERR);
459 GNUNET_SERVER_client_drop (tcc->client);
460 GNUNET_free (tcc->msg);
464 GNUNET_assert (size >= msize);
465 memcpy (buf, tcc->msg, msize);
466 GNUNET_SERVER_receive_done (tcc->client, GNUNET_OK);
467 GNUNET_SERVER_client_drop (tcc->client);
468 GNUNET_free (tcc->msg);
475 * Transmit the given message to the client.
477 * @param client target of the message
478 * @param msg message to transmit, will be freed!
481 transmit (struct GNUNET_SERVER_Client *client, struct GNUNET_MessageHeader *msg)
483 struct TransmitCallbackContext *tcc;
485 if (GNUNET_YES == cleaning_done)
488 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
489 "Shutdown in progress, aborting transmission.\n");
491 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
495 tcc = GNUNET_malloc (sizeof (struct TransmitCallbackContext));
497 tcc->client = client;
500 GNUNET_SERVER_notify_transmit_ready (client, ntohs (msg->size),
501 GNUNET_TIME_UNIT_FOREVER_REL,
502 &transmit_callback, tcc)))
505 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
510 GNUNET_SERVER_client_keep (client);
511 GNUNET_CONTAINER_DLL_insert (tcc_head, tcc_tail, tcc);
516 * Transmit a status code to the client.
518 * @param client receiver of the response
519 * @param code status code
520 * @param msg optional error message (can be NULL)
523 transmit_status (struct GNUNET_SERVER_Client *client, int code, const char *msg)
525 struct StatusMessage *sm;
529 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
530 "Transmitting `%s' message with value %d and message `%s'\n",
531 "STATUS", code, msg != NULL ? msg : "(none)");
533 slen = (msg == NULL) ? 0 : strlen (msg) + 1;
534 sm = GNUNET_malloc (sizeof (struct StatusMessage) + slen);
535 sm->header.size = htons (sizeof (struct StatusMessage) + slen);
536 sm->header.type = htons (GNUNET_MESSAGE_TYPE_DATASTORE_STATUS);
537 sm->status = htonl (code);
539 memcpy (&sm[1], msg, slen);
540 transmit (client, &sm->header);
546 * Function that will transmit the given datastore entry
549 * @param cls closure, pointer to the client (of type GNUNET_SERVER_Client).
550 * @param key key for the content
551 * @param size number of bytes in data
552 * @param data content stored
553 * @param type type of the content
554 * @param priority priority of the content
555 * @param anonymity anonymity-level for the content
556 * @param expiration expiration time for the content
557 * @param uid unique identifier for the datum;
558 * maybe 0 if no unique identifier is available
560 * @return GNUNET_SYSERR to abort the iteration, GNUNET_OK to continue,
561 * GNUNET_NO to delete the item and continue (if supported)
564 transmit_item (void *cls, const GNUNET_HashCode * key, uint32_t size,
565 const void *data, enum GNUNET_BLOCK_Type type, uint32_t priority,
566 uint32_t anonymity, struct GNUNET_TIME_Absolute expiration,
569 struct GNUNET_SERVER_Client *client = cls;
570 struct GNUNET_MessageHeader *end;
571 struct DataMessage *dm;
575 /* transmit 'DATA_END' */
577 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transmitting `%s' message\n",
580 end = GNUNET_malloc (sizeof (struct GNUNET_MessageHeader));
581 end->size = htons (sizeof (struct GNUNET_MessageHeader));
582 end->type = htons (GNUNET_MESSAGE_TYPE_DATASTORE_DATA_END);
583 transmit (client, end);
584 GNUNET_SERVER_client_drop (client);
587 GNUNET_assert (sizeof (struct DataMessage) + size <
588 GNUNET_SERVER_MAX_MESSAGE_SIZE);
589 dm = GNUNET_malloc (sizeof (struct DataMessage) + size);
590 dm->header.size = htons (sizeof (struct DataMessage) + size);
591 dm->header.type = htons (GNUNET_MESSAGE_TYPE_DATASTORE_DATA);
593 dm->size = htonl (size);
594 dm->type = htonl (type);
595 dm->priority = htonl (priority);
596 dm->anonymity = htonl (anonymity);
597 dm->replication = htonl (0);
598 dm->reserved = htonl (0);
599 dm->expiration = GNUNET_TIME_absolute_hton (expiration);
600 dm->uid = GNUNET_htonll (uid);
602 memcpy (&dm[1], data, size);
604 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
605 "Transmitting `%s' message for `%s' of type %u with expiration %llu (now: %llu)\n",
606 "DATA", GNUNET_h2s (key), type,
607 (unsigned long long) expiration.abs_value,
608 (unsigned long long) GNUNET_TIME_absolute_get ().abs_value);
610 GNUNET_STATISTICS_update (stats, gettext_noop ("# results found"), 1,
612 transmit (client, &dm->header);
613 GNUNET_SERVER_client_drop (client);
619 * Handle RESERVE-message.
622 * @param client identification of the client
623 * @param message the actual message
626 handle_reserve (void *cls, struct GNUNET_SERVER_Client *client,
627 const struct GNUNET_MessageHeader *message)
630 * Static counter to produce reservation identifiers.
632 static int reservation_gen;
634 const struct ReserveMessage *msg = (const struct ReserveMessage *) message;
635 struct ReservationList *e;
636 unsigned long long used;
637 unsigned long long req;
642 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Processing `%s' request\n", "RESERVE");
644 amount = GNUNET_ntohll (msg->amount);
645 entries = ntohl (msg->entries);
646 used = payload + reserved;
648 amount + ((unsigned long long) GNUNET_DATASTORE_ENTRY_OVERHEAD) * entries;
649 if (used + req > quota)
652 used = quota; /* cheat a bit for error message (to avoid negative numbers) */
653 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
655 ("Insufficient space (%llu bytes are available) to satisfy `%s' request for %llu bytes\n"),
656 quota - used, "RESERVE", req);
657 if (cache_size < req)
659 /* TODO: document this in the FAQ; essentially, if this
660 * message happens, the insertion request could be blocked
661 * by less-important content from migration because it is
662 * larger than 1/8th of the overall available space, and
663 * we only reserve 1/8th for "fresh" insertions */
664 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
666 ("The requested amount (%llu bytes) is larger than the cache size (%llu bytes)\n"),
668 transmit_status (client, 0,
670 ("Insufficient space to satisfy request and "
671 "requested amount is larger than cache size"));
675 transmit_status (client, 0,
676 gettext_noop ("Insufficient space to satisfy request"));
681 GNUNET_STATISTICS_set (stats, gettext_noop ("# reserved"), reserved,
683 e = GNUNET_malloc (sizeof (struct ReservationList));
684 e->next = reservations;
688 e->entries = entries;
689 e->rid = ++reservation_gen;
690 if (reservation_gen < 0)
691 reservation_gen = 0; /* wrap around */
692 transmit_status (client, e->rid, NULL);
697 * Handle RELEASE_RESERVE-message.
700 * @param client identification of the client
701 * @param message the actual message
704 handle_release_reserve (void *cls, struct GNUNET_SERVER_Client *client,
705 const struct GNUNET_MessageHeader *message)
707 const struct ReleaseReserveMessage *msg =
708 (const struct ReleaseReserveMessage *) message;
709 struct ReservationList *pos;
710 struct ReservationList *prev;
711 struct ReservationList *next;
712 int rid = ntohl (msg->rid);
713 unsigned long long rem;
716 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Processing `%s' request\n",
721 while (NULL != (pos = next))
732 ((unsigned long long) GNUNET_DATASTORE_ENTRY_OVERHEAD) * pos->entries;
733 GNUNET_assert (reserved >= rem);
735 GNUNET_STATISTICS_set (stats, gettext_noop ("# reserved"), reserved,
738 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
739 "Returning %llu remaining reserved bytes to storage pool\n",
743 transmit_status (client, GNUNET_OK, NULL);
749 transmit_status (client, GNUNET_SYSERR,
750 gettext_noop ("Could not find matching reservation"));
755 * Check that the given message is a valid data message.
757 * @return NULL if the message is not well-formed, otherwise the message
759 static const struct DataMessage *
760 check_data (const struct GNUNET_MessageHeader *message)
764 const struct DataMessage *dm;
766 size = ntohs (message->size);
767 if (size < sizeof (struct DataMessage))
772 dm = (const struct DataMessage *) message;
773 dsize = ntohl (dm->size);
774 if (size != dsize + sizeof (struct DataMessage))
784 * Context for a PUT request used to see if the content is
790 * Client to notify on completion.
792 struct GNUNET_SERVER_Client *client;
794 #if ! HAVE_UNALIGNED_64_ACCESS
798 /* followed by the 'struct DataMessage' */
803 * Actually put the data message.
805 * @param client sender of the message
806 * @param dm message with the data to store
809 execute_put (struct GNUNET_SERVER_Client *client, const struct DataMessage *dm)
815 size = ntohl (dm->size);
818 plugin->api->put (plugin->api->cls, &dm->key, size, &dm[1],
819 ntohl (dm->type), ntohl (dm->priority),
820 ntohl (dm->anonymity), ntohl (dm->replication),
821 GNUNET_TIME_absolute_ntoh (dm->expiration), &msg);
822 if (GNUNET_OK == ret)
824 GNUNET_STATISTICS_update (stats, gettext_noop ("# bytes stored"), size,
826 GNUNET_CONTAINER_bloomfilter_add (filter, &dm->key);
828 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
829 "Successfully stored %u bytes of type %u under key `%s'\n",
830 size, ntohl (dm->type), GNUNET_h2s (&dm->key));
833 transmit_status (client, ret, msg);
834 GNUNET_free_non_null (msg);
835 if (quota - reserved - cache_size < payload)
837 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
838 _("Need %llu bytes more space (%llu allowed, using %llu)\n"),
839 (unsigned long long) size + GNUNET_DATASTORE_ENTRY_OVERHEAD,
840 (unsigned long long) (quota - reserved - cache_size),
841 (unsigned long long) payload);
842 manage_space (size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
848 * Function that will check if the given datastore entry
849 * matches the put and if none match executes the put.
851 * @param cls closure, pointer to the client (of type 'struct PutContext').
852 * @param key key for the content
853 * @param size number of bytes in data
854 * @param data content stored
855 * @param type type of the content
856 * @param priority priority of the content
857 * @param anonymity anonymity-level for the content
858 * @param expiration expiration time for the content
859 * @param uid unique identifier for the datum;
860 * maybe 0 if no unique identifier is available
862 * @return GNUNET_OK usually
863 * GNUNET_NO to delete the item
866 check_present (void *cls, const GNUNET_HashCode * key, uint32_t size,
867 const void *data, enum GNUNET_BLOCK_Type type, uint32_t priority,
868 uint32_t anonymity, struct GNUNET_TIME_Absolute expiration,
871 struct PutContext *pc = cls;
872 const struct DataMessage *dm;
874 dm = (const struct DataMessage *) &pc[1];
877 execute_put (pc->client, dm);
878 GNUNET_SERVER_client_drop (pc->client);
882 if ((GNUNET_BLOCK_TYPE_FS_DBLOCK == type) ||
883 (GNUNET_BLOCK_TYPE_FS_IBLOCK == type) || ((size == ntohl (dm->size)) &&
885 memcmp (&dm[1], data, size))))
888 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
889 "Result already present in datastore\n");
891 /* FIXME: change API to allow increasing 'replication' counter */
892 if ((ntohl (dm->priority) > 0) ||
893 (GNUNET_TIME_absolute_ntoh (dm->expiration).abs_value >
894 expiration.abs_value))
895 plugin->api->update (plugin->api->cls, uid,
896 (int32_t) ntohl (dm->priority),
897 GNUNET_TIME_absolute_ntoh (dm->expiration), NULL);
898 transmit_status (pc->client, GNUNET_NO, NULL);
899 GNUNET_SERVER_client_drop (pc->client);
904 execute_put (pc->client, dm);
905 GNUNET_SERVER_client_drop (pc->client);
913 * Handle PUT-message.
916 * @param client identification of the client
917 * @param message the actual message
920 handle_put (void *cls, struct GNUNET_SERVER_Client *client,
921 const struct GNUNET_MessageHeader *message)
923 const struct DataMessage *dm = check_data (message);
925 struct ReservationList *pos;
926 struct PutContext *pc;
927 GNUNET_HashCode vhash;
930 if ((dm == NULL) || (ntohl (dm->type) == 0))
933 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
937 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
938 "Processing `%s' request for `%s' of type %u\n", "PUT",
939 GNUNET_h2s (&dm->key), ntohl (dm->type));
941 rid = ntohl (dm->rid);
942 size = ntohl (dm->size);
946 while ((NULL != pos) && (rid != pos->rid))
948 GNUNET_break (pos != NULL);
951 GNUNET_break (pos->entries > 0);
952 GNUNET_break (pos->amount >= size);
955 reserved -= (size + GNUNET_DATASTORE_ENTRY_OVERHEAD);
956 GNUNET_STATISTICS_set (stats, gettext_noop ("# reserved"), reserved,
960 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (filter, &dm->key))
962 GNUNET_CRYPTO_hash (&dm[1], size, &vhash);
963 pc = GNUNET_malloc (sizeof (struct PutContext) + size +
964 sizeof (struct DataMessage));
966 GNUNET_SERVER_client_keep (client);
967 memcpy (&pc[1], dm, size + sizeof (struct DataMessage));
968 plugin->api->get_key (plugin->api->cls, 0, &dm->key, &vhash,
969 ntohl (dm->type), &check_present, pc);
972 execute_put (client, dm);
977 * Handle GET-message.
980 * @param client identification of the client
981 * @param message the actual message
984 handle_get (void *cls, struct GNUNET_SERVER_Client *client,
985 const struct GNUNET_MessageHeader *message)
987 const struct GetMessage *msg;
990 size = ntohs (message->size);
991 if ((size != sizeof (struct GetMessage)) &&
992 (size != sizeof (struct GetMessage) - sizeof (GNUNET_HashCode)))
995 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
998 msg = (const struct GetMessage *) message;
1000 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1001 "Processing `%s' request for `%s' of type %u\n", "GET",
1002 GNUNET_h2s (&msg->key), ntohl (msg->type));
1004 GNUNET_STATISTICS_update (stats, gettext_noop ("# GET requests received"), 1,
1006 GNUNET_SERVER_client_keep (client);
1007 if ((size == sizeof (struct GetMessage)) &&
1008 (GNUNET_YES != GNUNET_CONTAINER_bloomfilter_test (filter, &msg->key)))
1010 /* don't bother database... */
1012 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1013 "Empty result set for `%s' request for `%s' (bloomfilter).\n",
1014 "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;
1051 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Processing `%s' request for %llu\n",
1052 "UPDATE", (unsigned long long) GNUNET_ntohll (msg->uid));
1055 plugin->api->update (plugin->api->cls, GNUNET_ntohll (msg->uid),
1056 (int32_t) ntohl (msg->priority),
1057 GNUNET_TIME_absolute_ntoh (msg->expiration), &emsg);
1058 transmit_status (client, ret, emsg);
1059 GNUNET_free_non_null (emsg);
1064 * Handle GET_REPLICATION-message.
1066 * @param cls closure
1067 * @param client identification of the client
1068 * @param message the actual message
1071 handle_get_replication (void *cls, struct GNUNET_SERVER_Client *client,
1072 const struct GNUNET_MessageHeader *message)
1075 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Processing `%s' request\n",
1078 GNUNET_STATISTICS_update (stats,
1080 ("# GET REPLICATION requests received"), 1,
1082 GNUNET_SERVER_client_keep (client);
1083 plugin->api->get_replication (plugin->api->cls, &transmit_item, client);
1088 * Handle GET_ZERO_ANONYMITY-message.
1090 * @param cls closure
1091 * @param client identification of the client
1092 * @param message the actual message
1095 handle_get_zero_anonymity (void *cls, struct GNUNET_SERVER_Client *client,
1096 const struct GNUNET_MessageHeader *message)
1098 const struct GetZeroAnonymityMessage *msg =
1099 (const struct GetZeroAnonymityMessage *) message;
1100 enum GNUNET_BLOCK_Type type;
1102 type = (enum GNUNET_BLOCK_Type) ntohl (msg->type);
1103 if (type == GNUNET_BLOCK_TYPE_ANY)
1106 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1110 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Processing `%s' request\n",
1111 "GET_ZERO_ANONYMITY");
1113 GNUNET_STATISTICS_update (stats,
1115 ("# GET ZERO ANONYMITY requests received"), 1,
1117 GNUNET_SERVER_client_keep (client);
1118 plugin->api->get_zero_anonymity (plugin->api->cls,
1119 GNUNET_ntohll (msg->offset), type,
1120 &transmit_item, client);
1125 * Callback function that will cause the item that is passed
1126 * in to be deleted (by returning GNUNET_NO).
1129 remove_callback (void *cls, const GNUNET_HashCode * key, uint32_t size,
1130 const void *data, enum GNUNET_BLOCK_Type type,
1131 uint32_t priority, uint32_t anonymity,
1132 struct GNUNET_TIME_Absolute expiration, uint64_t uid)
1134 struct GNUNET_SERVER_Client *client = cls;
1139 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1140 "No further matches for `%s' request.\n", "REMOVE");
1142 transmit_status (client, GNUNET_NO, _("Content not found"));
1143 GNUNET_SERVER_client_drop (client);
1144 return GNUNET_OK; /* last item */
1147 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1148 "Item %llu matches `%s' request for key `%s' and type %u.\n",
1149 (unsigned long long) uid, "REMOVE", GNUNET_h2s (key), type);
1151 GNUNET_STATISTICS_update (stats,
1152 gettext_noop ("# bytes removed (explicit request)"),
1154 GNUNET_CONTAINER_bloomfilter_remove (filter, key);
1155 transmit_status (client, GNUNET_OK, NULL);
1156 GNUNET_SERVER_client_drop (client);
1162 * Handle REMOVE-message.
1164 * @param cls closure
1165 * @param client identification of the client
1166 * @param message the actual message
1169 handle_remove (void *cls, struct GNUNET_SERVER_Client *client,
1170 const struct GNUNET_MessageHeader *message)
1172 const struct DataMessage *dm = check_data (message);
1173 GNUNET_HashCode vhash;
1178 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1182 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1183 "Processing `%s' request for `%s' of type %u\n", "REMOVE",
1184 GNUNET_h2s (&dm->key), ntohl (dm->type));
1186 GNUNET_STATISTICS_update (stats, gettext_noop ("# REMOVE requests received"),
1188 GNUNET_SERVER_client_keep (client);
1189 GNUNET_CRYPTO_hash (&dm[1], ntohl (dm->size), &vhash);
1190 plugin->api->get_key (plugin->api->cls, 0, &dm->key, &vhash,
1191 (enum GNUNET_BLOCK_Type) ntohl (dm->type),
1192 &remove_callback, client);
1197 * Handle DROP-message.
1199 * @param cls closure
1200 * @param client identification of the client
1201 * @param message the actual message
1204 handle_drop (void *cls, struct GNUNET_SERVER_Client *client,
1205 const struct GNUNET_MessageHeader *message)
1208 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Processing `%s' request\n", "DROP");
1210 do_drop = GNUNET_YES;
1211 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1216 * Function called by plugins to notify us about a
1217 * change in their disk utilization.
1219 * @param cls closure (NULL)
1220 * @param delta change in disk utilization,
1221 * 0 for "reset to empty"
1224 disk_utilization_change_cb (void *cls, int delta)
1226 if ((delta < 0) && (payload < -delta))
1228 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1230 ("Datastore payload inaccurate (%lld < %lld). Trying to fix.\n"),
1231 (long long) payload, (long long) -delta);
1232 payload = plugin->api->estimate_size (plugin->api->cls);
1238 if (lastSync >= MAX_STAT_SYNC_LAG)
1244 * Callback function to process statistic values.
1246 * @param cls closure (struct Plugin*)
1247 * @param subsystem name of subsystem that created the statistic
1248 * @param name the name of the datum
1249 * @param value the current value
1250 * @param is_persistent GNUNET_YES if the value is persistent, GNUNET_NO if not
1251 * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
1254 process_stat_in (void *cls, const char *subsystem, const char *name,
1255 uint64_t value, int is_persistent)
1257 GNUNET_assert (stats_worked == GNUNET_NO);
1258 stats_worked = GNUNET_YES;
1261 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1262 "Notification from statistics about existing payload (%llu), new payload is %llu\n",
1263 abs_value, payload);
1270 process_stat_done (void *cls, int success)
1272 struct DatastorePlugin *plugin = cls;
1275 if (stats_worked == GNUNET_NO)
1276 payload = plugin->api->estimate_size (plugin->api->cls);
1281 * Load the datastore plugin.
1283 static struct DatastorePlugin *
1286 struct DatastorePlugin *ret;
1291 GNUNET_CONFIGURATION_get_value_string (cfg, "DATASTORE", "DATABASE",
1294 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1295 _("No `%s' specified for `%s' in configuration!\n"), "DATABASE",
1299 ret = GNUNET_malloc (sizeof (struct DatastorePlugin));
1301 ret->env.duc = &disk_utilization_change_cb;
1302 ret->env.cls = NULL;
1303 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Loading `%s' datastore plugin\n"),
1305 GNUNET_asprintf (&libname, "libgnunet_plugin_datastore_%s", name);
1306 ret->short_name = name;
1307 ret->lib_name = libname;
1308 ret->api = GNUNET_PLUGIN_load (libname, &ret->env);
1309 if (ret->api == NULL)
1311 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1312 _("Failed to load datastore plugin for `%s'\n"), name);
1313 GNUNET_free (ret->short_name);
1314 GNUNET_free (libname);
1323 * Function called when the service shuts
1324 * down. Unloads our datastore plugin.
1326 * @param plug plugin to unload
1329 unload_plugin (struct DatastorePlugin *plug)
1332 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1333 "Datastore service is unloading plugin...\n");
1335 GNUNET_break (NULL == GNUNET_PLUGIN_unload (plug->lib_name, plug->api));
1336 GNUNET_free (plug->lib_name);
1337 GNUNET_free (plug->short_name);
1343 * Final task run after shutdown. Unloads plugins and disconnects us from
1347 unload_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1349 if (GNUNET_YES == do_drop)
1350 plugin->api->drop (plugin->api->cls);
1351 unload_plugin (plugin);
1355 GNUNET_CONTAINER_bloomfilter_free (filter);
1360 if (stat_get != NULL)
1362 GNUNET_STATISTICS_get_cancel (stat_get);
1367 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
1374 * Last task run during shutdown. Disconnects us from
1375 * the transport and core.
1378 cleaning_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1380 struct TransmitCallbackContext *tcc;
1382 cleaning_done = GNUNET_YES;
1383 while (NULL != (tcc = tcc_head))
1385 GNUNET_CONTAINER_DLL_remove (tcc_head, tcc_tail, tcc);
1386 if (tcc->th != NULL)
1388 GNUNET_CONNECTION_notify_transmit_ready_cancel (tcc->th);
1389 GNUNET_SERVER_client_drop (tcc->client);
1391 GNUNET_free (tcc->msg);
1394 if (expired_kill_task != GNUNET_SCHEDULER_NO_TASK)
1396 GNUNET_SCHEDULER_cancel (expired_kill_task);
1397 expired_kill_task = GNUNET_SCHEDULER_NO_TASK;
1399 GNUNET_SCHEDULER_add_continuation (&unload_task, NULL,
1400 GNUNET_SCHEDULER_REASON_PREREQ_DONE);
1405 * Function that removes all active reservations made
1406 * by the given client and releases the space for other
1409 * @param cls closure
1410 * @param client identification of the client
1413 cleanup_reservations (void *cls, struct GNUNET_SERVER_Client *client)
1415 struct ReservationList *pos;
1416 struct ReservationList *prev;
1417 struct ReservationList *next;
1426 if (pos->client == client)
1429 reservations = next;
1432 reserved -= pos->amount + pos->entries * GNUNET_DATASTORE_ENTRY_OVERHEAD;
1441 GNUNET_STATISTICS_set (stats, gettext_noop ("# reserved"), reserved,
1447 * Process datastore requests.
1449 * @param cls closure
1450 * @param server the initialized server
1451 * @param c configuration to use
1454 run (void *cls, struct GNUNET_SERVER_Handle *server,
1455 const struct GNUNET_CONFIGURATION_Handle *c)
1457 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1458 {&handle_reserve, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_RESERVE,
1459 sizeof (struct ReserveMessage)},
1460 {&handle_release_reserve, NULL,
1461 GNUNET_MESSAGE_TYPE_DATASTORE_RELEASE_RESERVE,
1462 sizeof (struct ReleaseReserveMessage)},
1463 {&handle_put, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_PUT, 0},
1464 {&handle_update, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_UPDATE,
1465 sizeof (struct UpdateMessage)},
1466 {&handle_get, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_GET, 0},
1467 {&handle_get_replication, NULL,
1468 GNUNET_MESSAGE_TYPE_DATASTORE_GET_REPLICATION,
1469 sizeof (struct GNUNET_MessageHeader)},
1470 {&handle_get_zero_anonymity, NULL,
1471 GNUNET_MESSAGE_TYPE_DATASTORE_GET_ZERO_ANONYMITY,
1472 sizeof (struct GetZeroAnonymityMessage)},
1473 {&handle_remove, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_REMOVE, 0},
1474 {&handle_drop, NULL, GNUNET_MESSAGE_TYPE_DATASTORE_DROP,
1475 sizeof (struct GNUNET_MessageHeader)},
1479 unsigned int bf_size;
1483 GNUNET_CONFIGURATION_get_value_number (cfg, "DATASTORE", "QUOTA", "a))
1485 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1486 _("No `%s' specified for `%s' in configuration!\n"), "QUOTA",
1490 stats = GNUNET_STATISTICS_create ("datastore", cfg);
1491 GNUNET_STATISTICS_set (stats, gettext_noop ("# quota"), quota, GNUNET_NO);
1492 cache_size = quota / 8; /* Or should we make this an option? */
1493 GNUNET_STATISTICS_set (stats, gettext_noop ("# cache size"), cache_size,
1495 bf_size = quota / 32; /* 8 bit per entry, 1 bit per 32 kb in DB */
1498 GNUNET_CONFIGURATION_get_value_filename (cfg, "DATASTORE", "BLOOMFILTER",
1500 (GNUNET_OK != GNUNET_DISK_directory_create_for_file (fn)))
1502 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1503 _("Could not use specified filename `%s' for bloomfilter.\n"),
1504 fn != NULL ? fn : "");
1505 GNUNET_free_non_null (fn);
1509 filter = GNUNET_CONTAINER_bloomfilter_load (fn, bf_size, 5); /* approx. 3% false positives at max use */
1511 filter = GNUNET_CONTAINER_bloomfilter_init (NULL, bf_size, 5); /* approx. 3% false positives at max use */
1512 GNUNET_free_non_null (fn);
1515 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1516 _("Failed to initialize bloomfilter.\n"));
1519 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
1524 plugin = load_plugin ();
1527 GNUNET_CONTAINER_bloomfilter_free (filter);
1531 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
1537 GNUNET_STATISTICS_get (stats, "datastore", QUOTA_STAT_NAME,
1538 GNUNET_TIME_UNIT_SECONDS, &process_stat_done,
1539 &process_stat_in, plugin);
1540 GNUNET_SERVER_disconnect_notify (server, &cleanup_reservations, NULL);
1541 GNUNET_SERVER_add_handlers (server, handlers);
1543 GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE,
1544 &delete_expired, NULL);
1545 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &cleaning_task,
1551 * The main function for the datastore service.
1553 * @param argc number of arguments from the command line
1554 * @param argv command line arguments
1555 * @return 0 ok, 1 on error
1558 main (int argc, char *const *argv)
1564 GNUNET_SERVICE_run (argc, argv, "datastore", GNUNET_SERVICE_OPTION_NONE,
1565 &run, NULL)) ? 0 : 1;
1570 /* end of gnunet-service-datastore.c */