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 /* Verbose logging callback */
81 void cdb_verbose_err(const DB_ENV *dbenv, const char *errpfx, const char *msg)
83 lprintf(CTDL_ALERT, "BDB: %s\n", msg);
87 /* just a little helper function */
88 static void txabort(DB_TXN * tid)
92 ret = tid->abort(tid);
95 lprintf(CTDL_EMERG, "cdb_*: txn_abort: %s\n",
101 /* this one is even more helpful than the last. */
102 static void txcommit(DB_TXN * tid)
106 ret = tid->commit(tid, 0);
109 lprintf(CTDL_EMERG, "cdb_*: txn_commit: %s\n",
115 /* are you sensing a pattern yet? */
116 static void txbegin(DB_TXN ** tid)
120 ret = dbenv->txn_begin(dbenv, NULL, tid, 0);
123 lprintf(CTDL_EMERG, "cdb_*: txn_begin: %s\n",
129 static void dbpanic(DB_ENV * env, int errval)
131 lprintf(CTDL_EMERG, "cdb_*: Berkeley DB panic: %d\n", errval);
134 static void cclose(DBC * cursor)
138 if ((ret = cursor->c_close(cursor))) {
139 lprintf(CTDL_EMERG, "cdb_*: c_close: %s\n",
145 static void bailIfCursor(DBC ** cursors, const char *msg)
149 for (i = 0; i < MAXCDB; i++)
150 if (cursors[i] != NULL) {
152 "cdb_*: cursor still in progress on cdb %d: %s\n",
158 static void check_handles(void *arg)
161 struct cdbtsd *tsd = (struct cdbtsd *) arg;
163 bailIfCursor(tsd->cursors, "in check_handles");
165 if (tsd->tid != NULL) {
167 "cdb_*: transaction still in progress!");
173 static void dest_tsd(void *arg)
182 * Ensure that we have a key for thread-specific data. We don't
183 * put anything in here that Citadel cares about; this is just database
184 * related stuff like cursors and transactions.
186 * This should be called immediately after startup by any thread which wants
187 * to use database calls, except for whatever thread calls open_databases.
189 void cdb_allocate_tsd(void)
193 if (pthread_getspecific(tsdkey) != NULL)
196 tsd = malloc(sizeof(struct cdbtsd));
200 memset(tsd->cursors, 0, sizeof tsd->cursors);
201 pthread_setspecific(tsdkey, tsd);
204 void cdb_free_tsd(void)
206 dest_tsd(pthread_getspecific(tsdkey));
207 pthread_setspecific(tsdkey, NULL);
210 void cdb_check_handles(void)
212 check_handles(pthread_getspecific(tsdkey));
217 * Reclaim unused space in the databases. We need to do each one of
218 * these discretely, rather than in a loop.
220 * This is a stub function in the Sleepycat DB backend, because there is no
221 * such API call available.
223 void defrag_databases(void)
230 * Cull the database logs
232 static void cdb_cull_logs(void)
241 /* Get the list of names. */
242 if ((ret = dbenv->log_archive(dbenv, &list, flags)) != 0) {
243 lprintf(CTDL_ERR, "cdb_cull_logs: %s\n", db_strerror(ret));
247 /* Print the list of names. */
249 for (file = list; *file != NULL; ++file) {
250 lprintf(CTDL_DEBUG, "Deleting log: %s\n", *file);
253 snprintf(errmsg, sizeof(errmsg),
254 " ** ERROR **\n \n \n "
255 "Citadel was unable to delete the "
256 "database log file '%s' because of the "
257 "following error:\n \n %s\n \n"
258 " This log file is no longer in use "
259 "and may be safely deleted.\n",
260 *file, strerror(errno));
261 aide_message(errmsg, "Database Warning Message");
269 * Manually initiate log file cull.
271 void cmd_cull(char *argbuf) {
272 if (CtdlAccessCheck(ac_internal)) return;
274 cprintf("%d Database log file cull completed.\n", CIT_OK);
279 * Request a checkpoint of the database.
281 static void cdb_checkpoint(void)
284 static time_t last_run = 0L;
286 /* Only do a checkpoint once per minute. */
287 if ((time(NULL) - last_run) < 60L) {
290 last_run = time(NULL);
292 lprintf(CTDL_DEBUG, "-- db checkpoint --\n");
293 ret = dbenv->txn_checkpoint(dbenv,
294 MAX_CHECKPOINT_KBYTES,
295 MAX_CHECKPOINT_MINUTES, 0);
298 lprintf(CTDL_EMERG, "cdb_checkpoint: txn_checkpoint: %s\n",
303 /* After a successful checkpoint, we can cull the unused logs */
304 if (config.c_auto_cull) {
311 * Main loop for the checkpoint thread.
313 void *checkpoint_thread(void *arg) {
314 struct CitContext checkpointCC;
316 lprintf(CTDL_DEBUG, "checkpoint_thread() initializing\n");
318 memset(&checkpointCC, 0, sizeof(struct CitContext));
319 checkpointCC.internal_pgm = 1;
320 checkpointCC.cs_pid = 0;
321 pthread_setspecific(MyConKey, (void *)&checkpointCC );
325 while (!time_to_die) {
330 lprintf(CTDL_DEBUG, "checkpoint_thread() exiting\n");
335 * Open the various databases we'll be using. Any database which
336 * does not exist should be created. Note that we don't need a
337 * critical section here, because there aren't any active threads
338 * manipulating the database yet.
340 void open_databases(void)
344 char dbfilename[SIZ];
347 lprintf(CTDL_DEBUG, "cdb_*: open_databases() starting\n");
348 lprintf(CTDL_DEBUG, "Compiled db: %s\n", DB_VERSION_STRING);
349 lprintf(CTDL_INFO, " Linked db: %s\n",
350 db_version(NULL, NULL, NULL));
352 lprintf(CTDL_INFO, "Linked zlib: %s\n", zlibVersion());
356 * Silently try to create the database subdirectory. If it's
357 * already there, no problem.
359 mkdir(ctdl_data_dir, 0700);
360 chmod(ctdl_data_dir, 0700);
361 chown(ctdl_data_dir, CTDLUID, (-1));
363 lprintf(CTDL_DEBUG, "cdb_*: Setting up DB environment\n");
364 db_env_set_func_yield(sched_yield);
365 ret = db_env_create(&dbenv, 0);
367 lprintf(CTDL_EMERG, "cdb_*: db_env_create: %s\n",
371 dbenv->set_errpfx(dbenv, "citserver");
372 dbenv->set_paniccall(dbenv, dbpanic);
373 dbenv->set_errcall(dbenv, cdb_verbose_err);
374 dbenv->set_errpfx(dbenv, "ctdl");
375 #if (DB_VERSION_MAJOR == 4) && (DB_VERSION_MINOR >= 3)
376 dbenv->set_msgcall(dbenv, cdb_verbose_log);
378 dbenv->set_verbose(dbenv, DB_VERB_DEADLOCK, 1);
379 dbenv->set_verbose(dbenv, DB_VERB_RECOVERY, 1);
382 * We want to specify the shared memory buffer pool cachesize,
383 * but everything else is the default.
385 ret = dbenv->set_cachesize(dbenv, 0, 64 * 1024, 0);
387 lprintf(CTDL_EMERG, "cdb_*: set_cachesize: %s\n",
389 dbenv->close(dbenv, 0);
393 if ((ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT))) {
394 lprintf(CTDL_EMERG, "cdb_*: set_lk_detect: %s\n",
396 dbenv->close(dbenv, 0);
401 DB_CREATE | DB_RECOVER | DB_INIT_MPOOL |
402 DB_PRIVATE | DB_INIT_TXN | DB_INIT_LOCK | DB_THREAD;
403 lprintf(CTDL_DEBUG, "dbenv->open(dbenv, %s, %d, 0)\n",
404 ctdl_data_dir, flags);
405 ret = dbenv->open(dbenv, ctdl_data_dir, flags, 0);
407 lprintf(CTDL_DEBUG, "cdb_*: dbenv->open: %s\n",
409 dbenv->close(dbenv, 0);
413 lprintf(CTDL_INFO, "cdb_*: Starting up DB\n");
415 for (i = 0; i < MAXCDB; ++i) {
417 /* Create a database handle */
418 ret = db_create(&dbp[i], dbenv, 0);
420 lprintf(CTDL_DEBUG, "cdb_*: db_create: %s\n",
426 /* Arbitrary names for our tables -- we reference them by
427 * number, so we don't have string names for them.
429 snprintf(dbfilename, sizeof dbfilename, "cdb.%02x", i);
431 ret = dbp[i]->open(dbp[i],
436 DB_CREATE | DB_AUTO_COMMIT | DB_THREAD,
439 lprintf(CTDL_EMERG, "cdb_*: db_open[%d]: %s\n", i,
445 if ((ret = pthread_key_create(&tsdkey, dest_tsd))) {
446 lprintf(CTDL_EMERG, "cdb_*: pthread_key_create: %s\n",
455 /* Make sure we own all the files, because in a few milliseconds
456 * we're going to drop root privs.
458 void cdb_chmod_data(void) {
461 char filename[PATH_MAX];
463 dp = opendir(ctdl_data_dir);
465 while (d = readdir(dp), d != NULL) {
466 if (d->d_name[0] != '.') {
467 snprintf(filename, sizeof filename,
468 "%s/%s", ctdl_data_dir, d->d_name);
469 lprintf(9, "chmod(%s, 0600) returned %d\n",
470 filename, chmod(filename, 0600)
472 lprintf(9, "chown(%s, CTDLUID, -1) returned %d\n",
473 filename, chown(filename, CTDLUID, (-1))
480 lprintf(CTDL_DEBUG, "cdb_*: open_databases() finished\n");
482 CtdlRegisterProtoHook(cmd_cull, "CULL", "Cull database logs");
487 * Close all of the db database files we've opened. This can be done
488 * in a loop, since it's just a bunch of closes.
490 void close_databases(void)
497 if ((ret = dbenv->txn_checkpoint(dbenv, 0, 0, 0))) {
499 "cdb_*: txn_checkpoint: %s\n", db_strerror(ret));
502 /* print some statistics... */
503 dbenv->lock_stat_print(dbenv, DB_STAT_ALL);
505 /* close the tables */
506 for (a = 0; a < MAXCDB; ++a) {
507 lprintf(CTDL_INFO, "cdb_*: Closing database %d\n", a);
508 ret = dbp[a]->close(dbp[a], 0);
511 "cdb_*: db_close: %s\n", db_strerror(ret));
516 /* Close the handle. */
517 ret = dbenv->close(dbenv, 0);
520 "cdb_*: DBENV->close: %s\n", db_strerror(ret));
526 * Compression functions only used if we have zlib
530 void cdb_decompress_if_necessary(struct cdbdata *cdb)
532 static int magic = COMPRESS_MAGIC;
533 struct CtdlCompressHeader zheader;
534 char *uncompressed_data;
535 char *compressed_data;
536 uLongf destLen, sourceLen;
540 if (cdb->ptr == NULL)
542 if (memcmp(cdb->ptr, &magic, sizeof(magic)))
545 /* At this point we know we're looking at a compressed item. */
546 memcpy(&zheader, cdb->ptr, sizeof(struct CtdlCompressHeader));
548 compressed_data = cdb->ptr;
549 compressed_data += sizeof(struct CtdlCompressHeader);
551 sourceLen = (uLongf) zheader.compressed_len;
552 destLen = (uLongf) zheader.uncompressed_len;
553 uncompressed_data = malloc(zheader.uncompressed_len);
555 if (uncompress((Bytef *) uncompressed_data,
556 (uLongf *) & destLen,
557 (const Bytef *) compressed_data,
558 (uLong) sourceLen) != Z_OK) {
559 lprintf(CTDL_EMERG, "uncompress() error\n");
564 cdb->len = (size_t) destLen;
565 cdb->ptr = uncompressed_data;
568 #endif /* HAVE_ZLIB */
572 * Store a piece of data. Returns 0 if the operation was successful. If a
573 * key already exists it should be overwritten.
575 int cdb_store(int cdb, void *ckey, int ckeylen, void *cdata, int cdatalen)
583 struct CtdlCompressHeader zheader;
584 char *compressed_data = NULL;
586 size_t buffer_len = 0;
590 memset(&dkey, 0, sizeof(DBT));
591 memset(&ddata, 0, sizeof(DBT));
594 ddata.size = cdatalen;
598 /* Only compress Visit records. Everything else is uncompressed. */
599 if (cdb == CDB_VISIT) {
601 zheader.magic = COMPRESS_MAGIC;
602 zheader.uncompressed_len = cdatalen;
603 buffer_len = ((cdatalen * 101) / 100) + 100
604 + sizeof(struct CtdlCompressHeader);
605 destLen = (uLongf) buffer_len;
606 compressed_data = malloc(buffer_len);
607 if (compress2((Bytef *) (compressed_data +
609 CtdlCompressHeader)),
610 &destLen, (Bytef *) cdata, (uLongf) cdatalen,
612 lprintf(CTDL_EMERG, "compress2() error\n");
615 zheader.compressed_len = (size_t) destLen;
616 memcpy(compressed_data, &zheader,
617 sizeof(struct CtdlCompressHeader));
618 ddata.size = (size_t) (sizeof(struct CtdlCompressHeader) +
619 zheader.compressed_len);
620 ddata.data = compressed_data;
625 ret = dbp[cdb]->put(dbp[cdb], /* db */
626 MYTID, /* transaction ID */
631 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n", cdb,
637 free(compressed_data);
642 bailIfCursor(MYCURSORS,
643 "attempt to write during r/o cursor");
648 if ((ret = dbp[cdb]->put(dbp[cdb], /* db */
649 tid, /* transaction ID */
653 if (ret == DB_LOCK_DEADLOCK) {
657 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n",
658 cdb, db_strerror(ret));
665 free(compressed_data);
674 * Delete a piece of data. Returns 0 if the operation was successful.
676 int cdb_delete(int cdb, void *key, int keylen)
683 memset(&dkey, 0, sizeof dkey);
688 ret = dbp[cdb]->del(dbp[cdb], MYTID, &dkey, 0);
690 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n", cdb,
692 if (ret != DB_NOTFOUND)
696 bailIfCursor(MYCURSORS,
697 "attempt to delete during r/o cursor");
702 if ((ret = dbp[cdb]->del(dbp[cdb], tid, &dkey, 0))
703 && ret != DB_NOTFOUND) {
704 if (ret == DB_LOCK_DEADLOCK) {
708 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n",
709 cdb, db_strerror(ret));
719 static DBC *localcursor(int cdb)
724 if (MYCURSORS[cdb] == NULL)
725 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &curs, 0);
728 MYCURSORS[cdb]->c_dup(MYCURSORS[cdb], &curs,
732 lprintf(CTDL_EMERG, "localcursor: %s\n", db_strerror(ret));
741 * Fetch a piece of data. If not found, returns NULL. Otherwise, it returns
742 * a struct cdbdata which it is the caller's responsibility to free later on
743 * using the cdb_free() routine.
745 struct cdbdata *cdb_fetch(int cdb, void *key, int keylen)
748 struct cdbdata *tempcdb;
752 memset(&dkey, 0, sizeof(DBT));
757 memset(&dret, 0, sizeof(DBT));
758 dret.flags = DB_DBT_MALLOC;
759 ret = dbp[cdb]->get(dbp[cdb], MYTID, &dkey, &dret, 0);
764 memset(&dret, 0, sizeof(DBT));
765 dret.flags = DB_DBT_MALLOC;
767 curs = localcursor(cdb);
769 ret = curs->c_get(curs, &dkey, &dret, DB_SET);
772 while (ret == DB_LOCK_DEADLOCK);
776 if ((ret != 0) && (ret != DB_NOTFOUND)) {
777 lprintf(CTDL_EMERG, "cdb_fetch(%d): %s\n", cdb,
784 tempcdb = (struct cdbdata *) malloc(sizeof(struct cdbdata));
786 if (tempcdb == NULL) {
788 "cdb_fetch: Cannot allocate memory for tempcdb\n");
792 tempcdb->len = dret.size;
793 tempcdb->ptr = dret.data;
795 cdb_decompress_if_necessary(tempcdb);
802 * Free a cdbdata item.
804 * Note that we only free the 'ptr' portion if it is not NULL. This allows
805 * other code to assume ownership of that memory simply by storing the
806 * pointer elsewhere and then setting 'ptr' to NULL. cdb_free() will then
809 void cdb_free(struct cdbdata *cdb)
817 void cdb_close_cursor(int cdb)
819 if (MYCURSORS[cdb] != NULL)
820 cclose(MYCURSORS[cdb]);
822 MYCURSORS[cdb] = NULL;
826 * Prepare for a sequential search of an entire database.
827 * (There is guaranteed to be no more than one traversal in
828 * progress per thread at any given time.)
830 void cdb_rewind(int cdb)
834 if (MYCURSORS[cdb] != NULL) {
836 "cdb_rewind: must close cursor on database %d before reopening.\n",
839 /* cclose(MYCURSORS[cdb]); */
843 * Now initialize the cursor
845 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &MYCURSORS[cdb], 0);
847 lprintf(CTDL_EMERG, "cdb_rewind: db_cursor: %s\n",
855 * Fetch the next item in a sequential search. Returns a pointer to a
856 * cdbdata structure, or NULL if we've hit the end.
858 struct cdbdata *cdb_next_item(int cdb)
861 struct cdbdata *cdbret;
864 /* Initialize the key/data pair so the flags aren't set. */
865 memset(&key, 0, sizeof(key));
866 memset(&data, 0, sizeof(data));
867 data.flags = DB_DBT_MALLOC;
869 ret = MYCURSORS[cdb]->c_get(MYCURSORS[cdb], &key, &data, DB_NEXT);
872 if (ret != DB_NOTFOUND) {
873 lprintf(CTDL_EMERG, "cdb_next_item(%d): %s\n",
874 cdb, db_strerror(ret));
877 cclose(MYCURSORS[cdb]);
878 MYCURSORS[cdb] = NULL;
879 return NULL; /* presumably, end of file */
882 cdbret = (struct cdbdata *) malloc(sizeof(struct cdbdata));
883 cdbret->len = data.size;
884 cdbret->ptr = data.data;
886 cdb_decompress_if_necessary(cdbret);
895 * Transaction-based stuff. I'm writing this as I bake cookies...
898 void cdb_begin_transaction(void)
901 bailIfCursor(MYCURSORS,
902 "can't begin transaction during r/o cursor");
906 "cdb_begin_transaction: ERROR: nested transaction\n");
913 void cdb_end_transaction(void)
917 for (i = 0; i < MAXCDB; i++)
918 if (MYCURSORS[i] != NULL) {
919 lprintf(CTDL_WARNING,
920 "cdb_end_transaction: WARNING: cursor %d still open at transaction end\n",
922 cclose(MYCURSORS[i]);
928 "cdb_end_transaction: ERROR: txcommit(NULL) !!\n");
937 * Truncate (delete every record)
939 void cdb_trunc(int cdb)
947 "cdb_trunc must not be called in a transaction.\n");
950 bailIfCursor(MYCURSORS,
951 "attempt to write during r/o cursor");
956 if ((ret = dbp[cdb]->truncate(dbp[cdb], /* db */
957 NULL, /* transaction ID */
958 &count, /* #rows deleted */
960 if (ret == DB_LOCK_DEADLOCK) {
965 "cdb_truncate(%d): %s\n", cdb,