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 "citserver.h"
52 #include "sysdep_decls.h"
55 #include "ctdl_module.h"
58 static DB *dbp[MAXCDB]; /* One DB handle for each Citadel database */
59 static DB_ENV *dbenv; /* The DB environment (global) */
61 struct cdbtsd { /* Thread-specific DB stuff */
62 DB_TXN *tid; /* Transaction handle */
63 DBC *cursors[MAXCDB]; /* Cursors, for traversals... */
70 static pthread_key_t tsdkey;
72 #define MYCURSORS (((struct cdbtsd*)pthread_getspecific(tsdkey))->cursors)
73 #define MYTID (((struct cdbtsd*)pthread_getspecific(tsdkey))->tid)
75 /* Verbose logging callback */
76 void cdb_verbose_log(const DB_ENV *dbenv, const char *msg)
78 lprintf(CTDL_DEBUG, "BDB: %s\n", msg);
82 /* Verbose logging callback */
83 void cdb_verbose_err(const DB_ENV *dbenv, const char *errpfx, const char *msg)
85 lprintf(CTDL_ALERT, "BDB: %s\n", msg);
89 /* just a little helper function */
90 static void txabort(DB_TXN * tid)
94 ret = tid->abort(tid);
97 lprintf(CTDL_EMERG, "cdb_*: txn_abort: %s\n",
103 /* this one is even more helpful than the last. */
104 static void txcommit(DB_TXN * tid)
108 ret = tid->commit(tid, 0);
111 lprintf(CTDL_EMERG, "cdb_*: txn_commit: %s\n",
117 /* are you sensing a pattern yet? */
118 static void txbegin(DB_TXN ** tid)
122 ret = dbenv->txn_begin(dbenv, NULL, tid, 0);
125 lprintf(CTDL_EMERG, "cdb_*: txn_begin: %s\n",
131 static void dbpanic(DB_ENV * env, int errval)
133 lprintf(CTDL_EMERG, "cdb_*: Berkeley DB panic: %d\n", errval);
136 static void cclose(DBC * cursor)
140 if ((ret = cursor->c_close(cursor))) {
141 lprintf(CTDL_EMERG, "cdb_*: c_close: %s\n",
147 static void bailIfCursor(DBC ** cursors, const char *msg)
151 for (i = 0; i < MAXCDB; i++)
152 if (cursors[i] != NULL) {
154 "cdb_*: cursor still in progress on cdb %d: %s\n",
160 static void check_handles(void *arg)
163 struct cdbtsd *tsd = (struct cdbtsd *) arg;
165 bailIfCursor(tsd->cursors, "in check_handles");
167 if (tsd->tid != NULL) {
169 "cdb_*: transaction still in progress!");
175 static void dest_tsd(void *arg)
184 * Ensure that we have a key for thread-specific data. We don't
185 * put anything in here that Citadel cares about; this is just database
186 * related stuff like cursors and transactions.
188 * This should be called immediately after startup by any thread which wants
189 * to use database calls, except for whatever thread calls open_databases.
191 void cdb_allocate_tsd(void)
195 if (pthread_getspecific(tsdkey) != NULL)
198 tsd = malloc(sizeof(struct cdbtsd));
202 memset(tsd->cursors, 0, sizeof tsd->cursors);
203 pthread_setspecific(tsdkey, tsd);
206 void cdb_free_tsd(void)
208 dest_tsd(pthread_getspecific(tsdkey));
209 pthread_setspecific(tsdkey, NULL);
212 void cdb_check_handles(void)
214 check_handles(pthread_getspecific(tsdkey));
219 * Reclaim unused space in the databases. We need to do each one of
220 * these discretely, rather than in a loop.
222 * This is a stub function in the Sleepycat DB backend, because there is no
223 * such API call available.
225 void defrag_databases(void)
232 * Cull the database logs
234 static void cdb_cull_logs(void)
243 /* Get the list of names. */
244 if ((ret = dbenv->log_archive(dbenv, &list, flags)) != 0) {
245 lprintf(CTDL_ERR, "cdb_cull_logs: %s\n", db_strerror(ret));
249 /* Print the list of names. */
251 for (file = list; *file != NULL; ++file) {
252 lprintf(CTDL_DEBUG, "Deleting log: %s\n", *file);
255 snprintf(errmsg, sizeof(errmsg),
256 " ** ERROR **\n \n \n "
257 "Citadel was unable to delete the "
258 "database log file '%s' because of the "
259 "following error:\n \n %s\n \n"
260 " This log file is no longer in use "
261 "and may be safely deleted.\n",
262 *file, strerror(errno));
263 aide_message(errmsg, "Database Warning Message");
271 * Manually initiate log file cull.
273 void cmd_cull(char *argbuf) {
274 if (CtdlAccessCheck(ac_internal)) return;
276 cprintf("%d Database log file cull completed.\n", CIT_OK);
281 * Request a checkpoint of the database.
283 void cdb_checkpoint(void)
286 // static time_t last_run = 0L;
288 /* Only do a checkpoint once per minute. */
290 * Don't need this any more, since the thread that calls us sleeps for 60 seconds between calls
292 if ((time(NULL) - last_run) < 60L) {
295 last_run = time(NULL);
298 lprintf(CTDL_DEBUG, "-- db checkpoint --\n");
299 ret = dbenv->txn_checkpoint(dbenv,
300 MAX_CHECKPOINT_KBYTES,
301 MAX_CHECKPOINT_MINUTES, 0);
304 lprintf(CTDL_EMERG, "cdb_checkpoint: txn_checkpoint: %s\n",
309 /* After a successful checkpoint, we can cull the unused logs */
310 if (config.c_auto_cull) {
318 * Open the various databases we'll be using. Any database which
319 * does not exist should be created. Note that we don't need a
320 * critical section here, because there aren't any active threads
321 * manipulating the database yet.
323 void open_databases(void)
327 char dbfilename[SIZ];
330 lprintf(CTDL_DEBUG, "cdb_*: open_databases() starting\n");
331 lprintf(CTDL_DEBUG, "Compiled db: %s\n", DB_VERSION_STRING);
332 lprintf(CTDL_INFO, " Linked db: %s\n",
333 db_version(NULL, NULL, NULL));
335 lprintf(CTDL_INFO, "Linked zlib: %s\n", zlibVersion());
339 * Silently try to create the database subdirectory. If it's
340 * already there, no problem.
342 mkdir(ctdl_data_dir, 0700);
343 chmod(ctdl_data_dir, 0700);
344 chown(ctdl_data_dir, CTDLUID, (-1));
346 lprintf(CTDL_DEBUG, "cdb_*: Setting up DB environment\n");
347 db_env_set_func_yield(sched_yield);
348 ret = db_env_create(&dbenv, 0);
350 lprintf(CTDL_EMERG, "cdb_*: db_env_create: %s\n",
354 dbenv->set_errpfx(dbenv, "citserver");
355 dbenv->set_paniccall(dbenv, dbpanic);
356 dbenv->set_errcall(dbenv, cdb_verbose_err);
357 dbenv->set_errpfx(dbenv, "ctdl");
358 #if (DB_VERSION_MAJOR == 4) && (DB_VERSION_MINOR >= 3)
359 dbenv->set_msgcall(dbenv, cdb_verbose_log);
361 dbenv->set_verbose(dbenv, DB_VERB_DEADLOCK, 1);
362 dbenv->set_verbose(dbenv, DB_VERB_RECOVERY, 1);
365 * We want to specify the shared memory buffer pool cachesize,
366 * but everything else is the default.
368 ret = dbenv->set_cachesize(dbenv, 0, 64 * 1024, 0);
370 lprintf(CTDL_EMERG, "cdb_*: set_cachesize: %s\n",
372 dbenv->close(dbenv, 0);
376 if ((ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT))) {
377 lprintf(CTDL_EMERG, "cdb_*: set_lk_detect: %s\n",
379 dbenv->close(dbenv, 0);
383 flags = DB_CREATE | DB_INIT_MPOOL | DB_PRIVATE | DB_INIT_TXN | DB_INIT_LOCK | DB_THREAD | DB_RECOVER;
384 lprintf(CTDL_DEBUG, "dbenv->open(dbenv, %s, %d, 0)\n", ctdl_data_dir, flags);
385 ret = dbenv->open(dbenv, ctdl_data_dir, flags, 0);
386 if (ret == DB_RUNRECOVERY) {
387 lprintf(CTDL_ALERT, "dbenv->open: %s\n", db_strerror(ret));
388 lprintf(CTDL_ALERT, "Attempting recovery...\n");
390 ret = dbenv->open(dbenv, ctdl_data_dir, flags, 0);
392 if (ret == DB_RUNRECOVERY) {
393 lprintf(CTDL_ALERT, "dbenv->open: %s\n", db_strerror(ret));
394 lprintf(CTDL_ALERT, "Attempting catastrophic recovery...\n");
395 flags &= ~DB_RECOVER;
396 flags |= DB_RECOVER_FATAL;
397 ret = dbenv->open(dbenv, ctdl_data_dir, flags, 0);
400 lprintf(CTDL_DEBUG, "dbenv->open: %s\n", db_strerror(ret));
401 dbenv->close(dbenv, 0);
405 lprintf(CTDL_INFO, "Starting up DB\n");
407 for (i = 0; i < MAXCDB; ++i) {
409 /* Create a database handle */
410 ret = db_create(&dbp[i], dbenv, 0);
412 lprintf(CTDL_DEBUG, "db_create: %s\n",
418 /* Arbitrary names for our tables -- we reference them by
419 * number, so we don't have string names for them.
421 snprintf(dbfilename, sizeof dbfilename, "cdb.%02x", i);
423 ret = dbp[i]->open(dbp[i],
428 DB_CREATE | DB_AUTO_COMMIT | DB_THREAD,
431 lprintf(CTDL_EMERG, "db_open[%d]: %s\n", i,
437 if ((ret = pthread_key_create(&tsdkey, dest_tsd))) {
438 lprintf(CTDL_EMERG, "pthread_key_create: %s\n",
448 /* Make sure we own all the files, because in a few milliseconds
449 * we're going to drop root privs.
451 void cdb_chmod_data(void) {
454 char filename[PATH_MAX];
456 dp = opendir(ctdl_data_dir);
458 while (d = readdir(dp), d != NULL) {
459 if (d->d_name[0] != '.') {
460 snprintf(filename, sizeof filename,
461 "%s/%s", ctdl_data_dir, d->d_name);
462 lprintf(9, "chmod(%s, 0600) returned %d\n",
463 filename, chmod(filename, 0600)
465 lprintf(9, "chown(%s, CTDLUID, -1) returned %d\n",
466 filename, chown(filename, CTDLUID, (-1))
473 lprintf(CTDL_DEBUG, "open_databases() finished\n");
475 CtdlRegisterProtoHook(cmd_cull, "CULL", "Cull database logs");
480 * Close all of the db database files we've opened. This can be done
481 * in a loop, since it's just a bunch of closes.
483 void close_databases(void)
490 if ((ret = dbenv->txn_checkpoint(dbenv, 0, 0, 0))) {
492 "txn_checkpoint: %s\n", db_strerror(ret));
495 /* print some statistics... */
497 dbenv->lock_stat_print(dbenv, DB_STAT_ALL);
500 /* close the tables */
501 for (a = 0; a < MAXCDB; ++a) {
502 lprintf(CTDL_INFO, "Closing database %d\n", a);
503 ret = dbp[a]->close(dbp[a], 0);
506 "db_close: %s\n", db_strerror(ret));
511 /* Close the handle. */
512 ret = dbenv->close(dbenv, 0);
515 "DBENV->close: %s\n", db_strerror(ret));
521 * Compression functions only used if we have zlib
525 void cdb_decompress_if_necessary(struct cdbdata *cdb)
527 static int magic = COMPRESS_MAGIC;
528 struct CtdlCompressHeader zheader;
529 char *uncompressed_data;
530 char *compressed_data;
531 uLongf destLen, sourceLen;
535 if (cdb->ptr == NULL)
537 if (memcmp(cdb->ptr, &magic, sizeof(magic)))
540 /* At this point we know we're looking at a compressed item. */
541 memcpy(&zheader, cdb->ptr, sizeof(struct CtdlCompressHeader));
543 compressed_data = cdb->ptr;
544 compressed_data += sizeof(struct CtdlCompressHeader);
546 sourceLen = (uLongf) zheader.compressed_len;
547 destLen = (uLongf) zheader.uncompressed_len;
548 uncompressed_data = malloc(zheader.uncompressed_len);
550 if (uncompress((Bytef *) uncompressed_data,
551 (uLongf *) & destLen,
552 (const Bytef *) compressed_data,
553 (uLong) sourceLen) != Z_OK) {
554 lprintf(CTDL_EMERG, "uncompress() error\n");
559 cdb->len = (size_t) destLen;
560 cdb->ptr = uncompressed_data;
563 #endif /* HAVE_ZLIB */
567 * Store a piece of data. Returns 0 if the operation was successful. If a
568 * key already exists it should be overwritten.
570 int cdb_store(int cdb, void *ckey, int ckeylen, void *cdata, int cdatalen)
578 struct CtdlCompressHeader zheader;
579 char *compressed_data = NULL;
581 size_t buffer_len = 0;
585 memset(&dkey, 0, sizeof(DBT));
586 memset(&ddata, 0, sizeof(DBT));
589 ddata.size = cdatalen;
593 /* Only compress Visit records. Everything else is uncompressed. */
594 if (cdb == CDB_VISIT) {
596 zheader.magic = COMPRESS_MAGIC;
597 zheader.uncompressed_len = cdatalen;
598 buffer_len = ((cdatalen * 101) / 100) + 100
599 + sizeof(struct CtdlCompressHeader);
600 destLen = (uLongf) buffer_len;
601 compressed_data = malloc(buffer_len);
602 if (compress2((Bytef *) (compressed_data +
604 CtdlCompressHeader)),
605 &destLen, (Bytef *) cdata, (uLongf) cdatalen,
607 lprintf(CTDL_EMERG, "compress2() error\n");
610 zheader.compressed_len = (size_t) destLen;
611 memcpy(compressed_data, &zheader,
612 sizeof(struct CtdlCompressHeader));
613 ddata.size = (size_t) (sizeof(struct CtdlCompressHeader) +
614 zheader.compressed_len);
615 ddata.data = compressed_data;
620 ret = dbp[cdb]->put(dbp[cdb], /* db */
621 MYTID, /* transaction ID */
626 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n", cdb,
632 free(compressed_data);
637 bailIfCursor(MYCURSORS,
638 "attempt to write during r/o cursor");
643 if ((ret = dbp[cdb]->put(dbp[cdb], /* db */
644 tid, /* transaction ID */
648 if (ret == DB_LOCK_DEADLOCK) {
652 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n",
653 cdb, db_strerror(ret));
660 free(compressed_data);
669 * Delete a piece of data. Returns 0 if the operation was successful.
671 int cdb_delete(int cdb, void *key, int keylen)
678 memset(&dkey, 0, sizeof dkey);
683 ret = dbp[cdb]->del(dbp[cdb], MYTID, &dkey, 0);
685 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n", cdb,
687 if (ret != DB_NOTFOUND)
691 bailIfCursor(MYCURSORS,
692 "attempt to delete during r/o cursor");
697 if ((ret = dbp[cdb]->del(dbp[cdb], tid, &dkey, 0))
698 && ret != DB_NOTFOUND) {
699 if (ret == DB_LOCK_DEADLOCK) {
703 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n",
704 cdb, db_strerror(ret));
714 static DBC *localcursor(int cdb)
719 if (MYCURSORS[cdb] == NULL)
720 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &curs, 0);
723 MYCURSORS[cdb]->c_dup(MYCURSORS[cdb], &curs,
727 lprintf(CTDL_EMERG, "localcursor: %s\n", db_strerror(ret));
736 * Fetch a piece of data. If not found, returns NULL. Otherwise, it returns
737 * a struct cdbdata which it is the caller's responsibility to free later on
738 * using the cdb_free() routine.
740 struct cdbdata *cdb_fetch(int cdb, void *key, int keylen)
743 struct cdbdata *tempcdb;
747 memset(&dkey, 0, sizeof(DBT));
752 memset(&dret, 0, sizeof(DBT));
753 dret.flags = DB_DBT_MALLOC;
754 ret = dbp[cdb]->get(dbp[cdb], MYTID, &dkey, &dret, 0);
759 memset(&dret, 0, sizeof(DBT));
760 dret.flags = DB_DBT_MALLOC;
762 curs = localcursor(cdb);
764 ret = curs->c_get(curs, &dkey, &dret, DB_SET);
767 while (ret == DB_LOCK_DEADLOCK);
771 if ((ret != 0) && (ret != DB_NOTFOUND)) {
772 lprintf(CTDL_EMERG, "cdb_fetch(%d): %s\n", cdb,
779 tempcdb = (struct cdbdata *) malloc(sizeof(struct cdbdata));
781 if (tempcdb == NULL) {
783 "cdb_fetch: Cannot allocate memory for tempcdb\n");
787 tempcdb->len = dret.size;
788 tempcdb->ptr = dret.data;
790 cdb_decompress_if_necessary(tempcdb);
797 * Free a cdbdata item.
799 * Note that we only free the 'ptr' portion if it is not NULL. This allows
800 * other code to assume ownership of that memory simply by storing the
801 * pointer elsewhere and then setting 'ptr' to NULL. cdb_free() will then
804 void cdb_free(struct cdbdata *cdb)
812 void cdb_close_cursor(int cdb)
814 if (MYCURSORS[cdb] != NULL)
815 cclose(MYCURSORS[cdb]);
817 MYCURSORS[cdb] = NULL;
821 * Prepare for a sequential search of an entire database.
822 * (There is guaranteed to be no more than one traversal in
823 * progress per thread at any given time.)
825 void cdb_rewind(int cdb)
829 if (MYCURSORS[cdb] != NULL) {
831 "cdb_rewind: must close cursor on database %d before reopening.\n",
834 /* cclose(MYCURSORS[cdb]); */
838 * Now initialize the cursor
840 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &MYCURSORS[cdb], 0);
842 lprintf(CTDL_EMERG, "cdb_rewind: db_cursor: %s\n",
850 * Fetch the next item in a sequential search. Returns a pointer to a
851 * cdbdata structure, or NULL if we've hit the end.
853 struct cdbdata *cdb_next_item(int cdb)
856 struct cdbdata *cdbret;
859 /* Initialize the key/data pair so the flags aren't set. */
860 memset(&key, 0, sizeof(key));
861 memset(&data, 0, sizeof(data));
862 data.flags = DB_DBT_MALLOC;
864 ret = MYCURSORS[cdb]->c_get(MYCURSORS[cdb], &key, &data, DB_NEXT);
867 if (ret != DB_NOTFOUND) {
868 lprintf(CTDL_EMERG, "cdb_next_item(%d): %s\n",
869 cdb, db_strerror(ret));
872 cclose(MYCURSORS[cdb]);
873 MYCURSORS[cdb] = NULL;
874 return NULL; /* presumably, end of file */
877 cdbret = (struct cdbdata *) malloc(sizeof(struct cdbdata));
878 cdbret->len = data.size;
879 cdbret->ptr = data.data;
881 cdb_decompress_if_necessary(cdbret);
890 * Transaction-based stuff. I'm writing this as I bake cookies...
893 void cdb_begin_transaction(void)
896 bailIfCursor(MYCURSORS,
897 "can't begin transaction during r/o cursor");
901 "cdb_begin_transaction: ERROR: nested transaction\n");
908 void cdb_end_transaction(void)
912 for (i = 0; i < MAXCDB; i++)
913 if (MYCURSORS[i] != NULL) {
914 lprintf(CTDL_WARNING,
915 "cdb_end_transaction: WARNING: cursor %d still open at transaction end\n",
917 cclose(MYCURSORS[i]);
923 "cdb_end_transaction: ERROR: txcommit(NULL) !!\n");
932 * Truncate (delete every record)
934 void cdb_trunc(int cdb)
942 "cdb_trunc must not be called in a transaction.\n");
945 bailIfCursor(MYCURSORS,
946 "attempt to write during r/o cursor");
951 if ((ret = dbp[cdb]->truncate(dbp[cdb], /* db */
952 NULL, /* transaction ID */
953 &count, /* #rows deleted */
955 if (ret == DB_LOCK_DEADLOCK) {
960 "cdb_truncate(%d): %s\n", cdb,