4 * Sleepycat (Berkeley) DB driver for Citadel
8 /*****************************************************************************
9 Tunable configuration parameters for the Sleepycat DB back end
10 *****************************************************************************/
12 /* Citadel will checkpoint the db at the end of every session, but only if
13 * the specified number of kilobytes has been written, or if the specified
14 * number of minutes has passed, since the last checkpoint.
16 #define MAX_CHECKPOINT_KBYTES 256
17 #define MAX_CHECKPOINT_MINUTES 15
19 /*****************************************************************************/
28 #include <sys/types.h>
34 #elif defined(HAVE_DB4_DB_H)
37 #error Neither <db.h> nor <db4/db.h> was found by configure. Install db4-devel.
41 #if DB_VERSION_MAJOR < 4 || DB_VERSION_MINOR < 1
42 #error Citadel requires Berkeley DB v4.1 or newer. Please upgrade.
49 #include "serv_extensions.h"
50 #include "citserver.h"
53 #include "sysdep_decls.h"
56 static DB *dbp[MAXCDB]; /* One DB handle for each Citadel database */
57 static DB_ENV *dbenv; /* The DB environment (global) */
59 struct cdbtsd { /* Thread-specific DB stuff */
60 DB_TXN *tid; /* Transaction handle */
61 DBC *cursors[MAXCDB]; /* Cursors, for traversals... */
68 static pthread_key_t tsdkey;
70 #define MYCURSORS (((struct cdbtsd*)pthread_getspecific(tsdkey))->cursors)
71 #define MYTID (((struct cdbtsd*)pthread_getspecific(tsdkey))->tid)
73 /* Verbose logging callback */
74 void cdb_verbose_log(const DB_ENV *dbenv, const char *msg)
76 lprintf(CTDL_DEBUG, "BDB: %s\n", msg);
80 /* just a little helper function */
81 static void txabort(DB_TXN * tid)
85 ret = tid->abort(tid);
88 lprintf(CTDL_EMERG, "cdb_*: txn_abort: %s\n",
94 /* this one is even more helpful than the last. */
95 static void txcommit(DB_TXN * tid)
99 ret = tid->commit(tid, 0);
102 lprintf(CTDL_EMERG, "cdb_*: txn_commit: %s\n",
108 /* are you sensing a pattern yet? */
109 static void txbegin(DB_TXN ** tid)
113 ret = dbenv->txn_begin(dbenv, NULL, tid, 0);
116 lprintf(CTDL_EMERG, "cdb_*: txn_begin: %s\n",
122 static void dbpanic(DB_ENV * env, int errval)
124 lprintf(CTDL_EMERG, "cdb_*: Berkeley DB panic: %d\n", errval);
127 static void cclose(DBC * cursor)
131 if ((ret = cursor->c_close(cursor))) {
132 lprintf(CTDL_EMERG, "cdb_*: c_close: %s\n",
138 static void bailIfCursor(DBC ** cursors, const char *msg)
142 for (i = 0; i < MAXCDB; i++)
143 if (cursors[i] != NULL) {
145 "cdb_*: cursor still in progress on cdb %d: %s\n",
151 static void check_handles(void *arg)
154 struct cdbtsd *tsd = (struct cdbtsd *) arg;
156 bailIfCursor(tsd->cursors, "in check_handles");
158 if (tsd->tid != NULL) {
160 "cdb_*: transaction still in progress!");
166 static void dest_tsd(void *arg)
175 * Ensure that we have a key for thread-specific data. We don't
176 * put anything in here that Citadel cares about; this is just database
177 * related stuff like cursors and transactions.
179 * This should be called immediately after startup by any thread which wants
180 * to use database calls, except for whatever thread calls open_databases.
182 void cdb_allocate_tsd(void)
186 if (pthread_getspecific(tsdkey) != NULL)
189 tsd = malloc(sizeof(struct cdbtsd));
193 memset(tsd->cursors, 0, sizeof tsd->cursors);
194 pthread_setspecific(tsdkey, tsd);
197 void cdb_free_tsd(void)
199 dest_tsd(pthread_getspecific(tsdkey));
200 pthread_setspecific(tsdkey, NULL);
203 void cdb_check_handles(void)
205 check_handles(pthread_getspecific(tsdkey));
210 * Reclaim unused space in the databases. We need to do each one of
211 * these discretely, rather than in a loop.
213 * This is a stub function in the Sleepycat DB backend, because there is no
214 * such API call available.
216 void defrag_databases(void)
223 * Cull the database logs
225 static void cdb_cull_logs(void)
234 /* Get the list of names. */
235 if ((ret = dbenv->log_archive(dbenv, &list, flags)) != 0) {
236 lprintf(CTDL_ERR, "cdb_cull_logs: %s\n", db_strerror(ret));
240 /* Print the list of names. */
242 for (file = list; *file != NULL; ++file) {
243 lprintf(CTDL_DEBUG, "Deleting log: %s\n", *file);
246 snprintf(errmsg, sizeof(errmsg),
247 " ** ERROR **\n \n \n "
248 "Citadel was unable to delete the "
249 "database log file '%s' because of the "
250 "following error:\n \n %s\n \n"
251 " This log file is no longer in use "
252 "and may be safely deleted.\n",
253 *file, strerror(errno));
254 aide_message(errmsg, "Database Warning Message");
262 * Manually initiate log file cull.
264 void cmd_cull(char *argbuf) {
265 if (CtdlAccessCheck(ac_internal)) return;
267 cprintf("%d Database log file cull completed.\n", CIT_OK);
272 * Request a checkpoint of the database.
274 static void cdb_checkpoint(void)
277 static time_t last_run = 0L;
279 /* Only do a checkpoint once per minute. */
280 if ((time(NULL) - last_run) < 60L) {
283 last_run = time(NULL);
285 lprintf(CTDL_DEBUG, "-- db checkpoint --\n");
286 ret = dbenv->txn_checkpoint(dbenv,
287 MAX_CHECKPOINT_KBYTES,
288 MAX_CHECKPOINT_MINUTES, 0);
291 lprintf(CTDL_EMERG, "cdb_checkpoint: txn_checkpoint: %s\n",
296 /* After a successful checkpoint, we can cull the unused logs */
297 if (config.c_auto_cull) {
304 * Main loop for the checkpoint thread.
306 void *checkpoint_thread(void *arg) {
307 struct CitContext checkpointCC;
309 lprintf(CTDL_DEBUG, "checkpoint_thread() initializing\n");
311 memset(&checkpointCC, 0, sizeof(struct CitContext));
312 checkpointCC.internal_pgm = 1;
313 checkpointCC.cs_pid = 0;
314 pthread_setspecific(MyConKey, (void *)&checkpointCC );
318 while (!time_to_die) {
323 lprintf(CTDL_DEBUG, "checkpoint_thread() exiting\n");
328 * Open the various databases we'll be using. Any database which
329 * does not exist should be created. Note that we don't need a
330 * critical section here, because there aren't any active threads
331 * manipulating the database yet.
333 void open_databases(void)
337 char dbfilename[SIZ];
341 char filename[PATH_MAX];
343 lprintf(CTDL_DEBUG, "cdb_*: open_databases() starting\n");
344 lprintf(CTDL_DEBUG, "Compiled db: %s\n", DB_VERSION_STRING);
345 lprintf(CTDL_INFO, " Linked db: %s\n",
346 db_version(NULL, NULL, NULL));
348 lprintf(CTDL_INFO, "Linked zlib: %s\n", zlibVersion());
352 * Silently try to create the database subdirectory. If it's
353 * already there, no problem.
355 mkdir(ctdl_data_dir, 0700);
356 chmod(ctdl_data_dir, 0700);
357 chown(ctdl_data_dir, CTDLUID, (-1));
359 lprintf(CTDL_DEBUG, "cdb_*: Setting up DB environment\n");
360 db_env_set_func_yield(sched_yield);
361 ret = db_env_create(&dbenv, 0);
363 lprintf(CTDL_EMERG, "cdb_*: db_env_create: %s\n",
367 dbenv->set_errpfx(dbenv, "citserver");
368 dbenv->set_paniccall(dbenv, dbpanic);
369 dbenv->set_msgcall(dbenv, cdb_verbose_log);
370 dbenv->set_verbose(dbenv, DB_VERB_DEADLOCK, 1);
371 dbenv->set_verbose(dbenv, DB_VERB_RECOVERY, 1);
372 dbenv->set_verbose(dbenv, DB_VERB_REGISTER, 1);
375 * We want to specify the shared memory buffer pool cachesize,
376 * but everything else is the default.
378 ret = dbenv->set_cachesize(dbenv, 0, 64 * 1024, 0);
380 lprintf(CTDL_EMERG, "cdb_*: set_cachesize: %s\n",
382 dbenv->close(dbenv, 0);
386 if ((ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT))) {
387 lprintf(CTDL_EMERG, "cdb_*: set_lk_detect: %s\n",
389 dbenv->close(dbenv, 0);
394 DB_CREATE | DB_RECOVER | DB_INIT_MPOOL |
395 DB_PRIVATE | DB_INIT_TXN | DB_INIT_LOCK | DB_THREAD;
396 lprintf(CTDL_DEBUG, "dbenv->open(dbenv, %s, %d, 0)\n",
397 ctdl_data_dir, flags);
398 ret = dbenv->open(dbenv, ctdl_data_dir, flags, 0);
400 lprintf(CTDL_DEBUG, "cdb_*: dbenv->open: %s\n",
402 dbenv->close(dbenv, 0);
406 lprintf(CTDL_INFO, "cdb_*: Starting up DB\n");
408 for (i = 0; i < MAXCDB; ++i) {
410 /* Create a database handle */
411 ret = db_create(&dbp[i], dbenv, 0);
413 lprintf(CTDL_DEBUG, "cdb_*: db_create: %s\n",
419 /* Arbitrary names for our tables -- we reference them by
420 * number, so we don't have string names for them.
422 snprintf(dbfilename, sizeof dbfilename, "cdb.%02x", i);
424 ret = dbp[i]->open(dbp[i],
429 DB_CREATE | DB_AUTO_COMMIT | DB_THREAD,
432 lprintf(CTDL_EMERG, "cdb_*: db_open[%d]: %s\n", i,
438 if ((ret = pthread_key_create(&tsdkey, dest_tsd))) {
439 lprintf(CTDL_EMERG, "cdb_*: pthread_key_create: %s\n",
446 /* Now make sure we own all the files, because in a few milliseconds
447 * we're going to drop root privs.
449 dp = opendir(ctdl_data_dir);
451 while (d = readdir(dp), d != NULL) {
452 if (d->d_name[0] != '.') {
453 snprintf(filename, sizeof filename,
454 "%s/%s", ctdl_data_dir, d->d_name);
455 chmod(filename, 0600);
456 chown(filename, CTDLUID, (-1));
462 lprintf(CTDL_DEBUG, "cdb_*: open_databases() finished\n");
464 CtdlRegisterProtoHook(cmd_cull, "CULL", "Cull database logs");
469 * Close all of the db database files we've opened. This can be done
470 * in a loop, since it's just a bunch of closes.
472 void close_databases(void)
479 if ((ret = dbenv->txn_checkpoint(dbenv, 0, 0, 0))) {
481 "cdb_*: txn_checkpoint: %s\n", db_strerror(ret));
484 for (a = 0; a < MAXCDB; ++a) {
485 lprintf(CTDL_INFO, "cdb_*: Closing database %d\n", a);
486 ret = dbp[a]->close(dbp[a], 0);
489 "cdb_*: db_close: %s\n", db_strerror(ret));
494 /* Close the handle. */
495 ret = dbenv->close(dbenv, 0);
498 "cdb_*: DBENV->close: %s\n", db_strerror(ret));
504 * Compression functions only used if we have zlib
508 void cdb_decompress_if_necessary(struct cdbdata *cdb)
510 static int magic = COMPRESS_MAGIC;
511 struct CtdlCompressHeader zheader;
512 char *uncompressed_data;
513 char *compressed_data;
514 uLongf destLen, sourceLen;
518 if (cdb->ptr == NULL)
520 if (memcmp(cdb->ptr, &magic, sizeof(magic)))
523 /* At this point we know we're looking at a compressed item. */
524 memcpy(&zheader, cdb->ptr, sizeof(struct CtdlCompressHeader));
526 compressed_data = cdb->ptr;
527 compressed_data += sizeof(struct CtdlCompressHeader);
529 sourceLen = (uLongf) zheader.compressed_len;
530 destLen = (uLongf) zheader.uncompressed_len;
531 uncompressed_data = malloc(zheader.uncompressed_len);
533 if (uncompress((Bytef *) uncompressed_data,
534 (uLongf *) & destLen,
535 (const Bytef *) compressed_data,
536 (uLong) sourceLen) != Z_OK) {
537 lprintf(CTDL_EMERG, "uncompress() error\n");
542 cdb->len = (size_t) destLen;
543 cdb->ptr = uncompressed_data;
546 #endif /* HAVE_ZLIB */
550 * Store a piece of data. Returns 0 if the operation was successful. If a
551 * key already exists it should be overwritten.
553 int cdb_store(int cdb, void *ckey, int ckeylen, void *cdata, int cdatalen)
561 struct CtdlCompressHeader zheader;
562 char *compressed_data = NULL;
568 memset(&dkey, 0, sizeof(DBT));
569 memset(&ddata, 0, sizeof(DBT));
572 ddata.size = cdatalen;
576 /* Only compress Visit records. Everything else is uncompressed. */
577 if (cdb == CDB_VISIT) {
579 zheader.magic = COMPRESS_MAGIC;
580 zheader.uncompressed_len = cdatalen;
581 buffer_len = ((cdatalen * 101) / 100) + 100
582 + sizeof(struct CtdlCompressHeader);
583 destLen = (uLongf) buffer_len;
584 compressed_data = malloc(buffer_len);
585 if (compress2((Bytef *) (compressed_data +
587 CtdlCompressHeader)),
588 &destLen, (Bytef *) cdata, (uLongf) cdatalen,
590 lprintf(CTDL_EMERG, "compress2() error\n");
593 zheader.compressed_len = (size_t) destLen;
594 memcpy(compressed_data, &zheader,
595 sizeof(struct CtdlCompressHeader));
596 ddata.size = (size_t) (sizeof(struct CtdlCompressHeader) +
597 zheader.compressed_len);
598 ddata.data = compressed_data;
603 ret = dbp[cdb]->put(dbp[cdb], /* db */
604 MYTID, /* transaction ID */
609 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n", cdb,
615 free(compressed_data);
620 bailIfCursor(MYCURSORS,
621 "attempt to write during r/o cursor");
626 if ((ret = dbp[cdb]->put(dbp[cdb], /* db */
627 tid, /* transaction ID */
631 if (ret == DB_LOCK_DEADLOCK) {
635 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n",
636 cdb, db_strerror(ret));
643 free(compressed_data);
652 * Delete a piece of data. Returns 0 if the operation was successful.
654 int cdb_delete(int cdb, void *key, int keylen)
661 memset(&dkey, 0, sizeof dkey);
666 ret = dbp[cdb]->del(dbp[cdb], MYTID, &dkey, 0);
668 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n", cdb,
670 if (ret != DB_NOTFOUND)
674 bailIfCursor(MYCURSORS,
675 "attempt to delete during r/o cursor");
680 if ((ret = dbp[cdb]->del(dbp[cdb], tid, &dkey, 0))
681 && ret != DB_NOTFOUND) {
682 if (ret == DB_LOCK_DEADLOCK) {
686 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n",
687 cdb, db_strerror(ret));
697 static DBC *localcursor(int cdb)
702 if (MYCURSORS[cdb] == NULL)
703 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &curs, 0);
706 MYCURSORS[cdb]->c_dup(MYCURSORS[cdb], &curs,
710 lprintf(CTDL_EMERG, "localcursor: %s\n", db_strerror(ret));
719 * Fetch a piece of data. If not found, returns NULL. Otherwise, it returns
720 * a struct cdbdata which it is the caller's responsibility to free later on
721 * using the cdb_free() routine.
723 struct cdbdata *cdb_fetch(int cdb, void *key, int keylen)
726 struct cdbdata *tempcdb;
730 memset(&dkey, 0, sizeof(DBT));
735 memset(&dret, 0, sizeof(DBT));
736 dret.flags = DB_DBT_MALLOC;
737 ret = dbp[cdb]->get(dbp[cdb], MYTID, &dkey, &dret, 0);
742 memset(&dret, 0, sizeof(DBT));
743 dret.flags = DB_DBT_MALLOC;
745 curs = localcursor(cdb);
747 ret = curs->c_get(curs, &dkey, &dret, DB_SET);
750 while (ret == DB_LOCK_DEADLOCK);
754 if ((ret != 0) && (ret != DB_NOTFOUND)) {
755 lprintf(CTDL_EMERG, "cdb_fetch(%d): %s\n", cdb,
762 tempcdb = (struct cdbdata *) malloc(sizeof(struct cdbdata));
764 if (tempcdb == NULL) {
766 "cdb_fetch: Cannot allocate memory for tempcdb\n");
770 tempcdb->len = dret.size;
771 tempcdb->ptr = dret.data;
773 cdb_decompress_if_necessary(tempcdb);
780 * Free a cdbdata item.
782 * Note that we only free the 'ptr' portion if it is not NULL. This allows
783 * other code to assume ownership of that memory simply by storing the
784 * pointer elsewhere and then setting 'ptr' to NULL. cdb_free() will then
787 void cdb_free(struct cdbdata *cdb)
795 void cdb_close_cursor(int cdb)
797 if (MYCURSORS[cdb] != NULL)
798 cclose(MYCURSORS[cdb]);
800 MYCURSORS[cdb] = NULL;
804 * Prepare for a sequential search of an entire database.
805 * (There is guaranteed to be no more than one traversal in
806 * progress per thread at any given time.)
808 void cdb_rewind(int cdb)
812 if (MYCURSORS[cdb] != NULL) {
814 "cdb_rewind: must close cursor on database %d before reopening.\n",
817 /* cclose(MYCURSORS[cdb]); */
821 * Now initialize the cursor
823 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &MYCURSORS[cdb], 0);
825 lprintf(CTDL_EMERG, "cdb_rewind: db_cursor: %s\n",
833 * Fetch the next item in a sequential search. Returns a pointer to a
834 * cdbdata structure, or NULL if we've hit the end.
836 struct cdbdata *cdb_next_item(int cdb)
839 struct cdbdata *cdbret;
842 /* Initialize the key/data pair so the flags aren't set. */
843 memset(&key, 0, sizeof(key));
844 memset(&data, 0, sizeof(data));
845 data.flags = DB_DBT_MALLOC;
847 ret = MYCURSORS[cdb]->c_get(MYCURSORS[cdb], &key, &data, DB_NEXT);
850 if (ret != DB_NOTFOUND) {
851 lprintf(CTDL_EMERG, "cdb_next_item(%d): %s\n",
852 cdb, db_strerror(ret));
855 cclose(MYCURSORS[cdb]);
856 MYCURSORS[cdb] = NULL;
857 return NULL; /* presumably, end of file */
860 cdbret = (struct cdbdata *) malloc(sizeof(struct cdbdata));
861 cdbret->len = data.size;
862 cdbret->ptr = data.data;
864 cdb_decompress_if_necessary(cdbret);
873 * Transaction-based stuff. I'm writing this as I bake cookies...
876 void cdb_begin_transaction(void)
879 bailIfCursor(MYCURSORS,
880 "can't begin transaction during r/o cursor");
884 "cdb_begin_transaction: ERROR: nested transaction\n");
891 void cdb_end_transaction(void)
895 for (i = 0; i < MAXCDB; i++)
896 if (MYCURSORS[i] != NULL) {
897 lprintf(CTDL_WARNING,
898 "cdb_end_transaction: WARNING: cursor %d still open at transaction end\n",
900 cclose(MYCURSORS[i]);
906 "cdb_end_transaction: ERROR: txcommit(NULL) !!\n");
915 * Truncate (delete every record)
917 void cdb_trunc(int cdb)
925 "cdb_trunc must not be called in a transaction.\n");
928 bailIfCursor(MYCURSORS,
929 "attempt to write during r/o cursor");
934 if ((ret = dbp[cdb]->truncate(dbp[cdb], /* db */
935 NULL, /* transaction ID */
936 &count, /* #rows deleted */
938 if (ret == DB_LOCK_DEADLOCK) {
943 "cdb_truncate(%d): %s\n", cdb,