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.
48 #include "citserver.h"
51 #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) */
67 /* Verbose logging callback */
68 void cdb_verbose_log(const DB_ENV *dbenv, const char *msg)
70 lprintf(CTDL_DEBUG, "BDB: %s\n", msg);
74 /* Verbose logging callback */
75 void cdb_verbose_err(const DB_ENV *dbenv, const char *errpfx, const char *msg)
77 lprintf(CTDL_ALERT, "BDB: %s\n", msg);
81 /* just a little helper function */
82 static void txabort(DB_TXN * tid)
86 ret = tid->abort(tid);
89 lprintf(CTDL_EMERG, "cdb_*: txn_abort: %s\n",
95 /* this one is even more helpful than the last. */
96 static void txcommit(DB_TXN * tid)
100 ret = tid->commit(tid, 0);
103 lprintf(CTDL_EMERG, "cdb_*: txn_commit: %s\n",
109 /* are you sensing a pattern yet? */
110 static void txbegin(DB_TXN ** tid)
114 ret = dbenv->txn_begin(dbenv, NULL, tid, 0);
117 lprintf(CTDL_EMERG, "cdb_*: txn_begin: %s\n",
123 static void dbpanic(DB_ENV * env, int errval)
125 lprintf(CTDL_EMERG, "cdb_*: Berkeley DB panic: %d\n", errval);
128 static void cclose(DBC * cursor)
132 if ((ret = cursor->c_close(cursor))) {
133 lprintf(CTDL_EMERG, "cdb_*: c_close: %s\n",
139 static void bailIfCursor(DBC ** cursors, const char *msg)
143 for (i = 0; i < MAXCDB; i++)
144 if (cursors[i] != NULL) {
146 "cdb_*: cursor still in progress on cdb %d: %s\n",
152 void check_handles(void *arg)
155 ThreadTSD *tsd = (ThreadTSD *) arg;
157 bailIfCursor(tsd->cursors, "in check_handles");
159 if (tsd->tid != NULL) {
161 "cdb_*: transaction still in progress!");
167 void cdb_check_handles(void)
169 check_handles(pthread_getspecific(ThreadKey));
174 * Cull the database logs
176 static void cdb_cull_logs(void)
185 /* Get the list of names. */
186 if ((ret = dbenv->log_archive(dbenv, &list, flags)) != 0) {
187 lprintf(CTDL_ERR, "cdb_cull_logs: %s\n", db_strerror(ret));
191 /* Print the list of names. */
193 for (file = list; *file != NULL; ++file) {
194 lprintf(CTDL_DEBUG, "Deleting log: %s\n", *file);
197 snprintf(errmsg, sizeof(errmsg),
198 " ** ERROR **\n \n \n "
199 "Citadel was unable to delete the "
200 "database log file '%s' because of the "
201 "following error:\n \n %s\n \n"
202 " This log file is no longer in use "
203 "and may be safely deleted.\n",
204 *file, strerror(errno));
205 aide_message(errmsg, "Database Warning Message");
213 * Manually initiate log file cull.
215 void cmd_cull(char *argbuf) {
216 if (CtdlAccessCheck(ac_internal)) return;
218 cprintf("%d Database log file cull completed.\n", CIT_OK);
223 * Request a checkpoint of the database.
225 void cdb_checkpoint(void)
228 // static time_t last_run = 0L;
230 /* Only do a checkpoint once per minute. */
232 * Don't need this any more, since the thread that calls us sleeps for 60 seconds between calls
234 if ((time(NULL) - last_run) < 60L) {
237 last_run = time(NULL);
240 lprintf(CTDL_DEBUG, "-- db checkpoint --\n");
241 ret = dbenv->txn_checkpoint(dbenv,
242 MAX_CHECKPOINT_KBYTES,
243 MAX_CHECKPOINT_MINUTES, 0);
246 lprintf(CTDL_EMERG, "cdb_checkpoint: txn_checkpoint: %s\n",
251 /* After a successful checkpoint, we can cull the unused logs */
252 if (config.c_auto_cull) {
260 * Open the various databases we'll be using. Any database which
261 * does not exist should be created. Note that we don't need a
262 * critical section here, because there aren't any active threads
263 * manipulating the database yet.
265 void open_databases(void)
269 char dbfilename[SIZ];
272 lprintf(CTDL_DEBUG, "cdb_*: open_databases() starting\n");
273 lprintf(CTDL_DEBUG, "Compiled db: %s\n", DB_VERSION_STRING);
274 lprintf(CTDL_INFO, " Linked db: %s\n",
275 db_version(NULL, NULL, NULL));
277 lprintf(CTDL_INFO, "Linked zlib: %s\n", zlibVersion());
281 * Silently try to create the database subdirectory. If it's
282 * already there, no problem.
284 mkdir(ctdl_data_dir, 0700);
285 chmod(ctdl_data_dir, 0700);
286 chown(ctdl_data_dir, CTDLUID, (-1));
288 lprintf(CTDL_DEBUG, "cdb_*: Setting up DB environment\n");
289 db_env_set_func_yield(sched_yield);
290 ret = db_env_create(&dbenv, 0);
292 lprintf(CTDL_EMERG, "cdb_*: db_env_create: %s\n",
296 dbenv->set_errpfx(dbenv, "citserver");
297 dbenv->set_paniccall(dbenv, dbpanic);
298 dbenv->set_errcall(dbenv, cdb_verbose_err);
299 dbenv->set_errpfx(dbenv, "ctdl");
300 #if (DB_VERSION_MAJOR == 4) && (DB_VERSION_MINOR >= 3)
301 dbenv->set_msgcall(dbenv, cdb_verbose_log);
303 dbenv->set_verbose(dbenv, DB_VERB_DEADLOCK, 1);
304 dbenv->set_verbose(dbenv, DB_VERB_RECOVERY, 1);
307 * We want to specify the shared memory buffer pool cachesize,
308 * but everything else is the default.
310 ret = dbenv->set_cachesize(dbenv, 0, 64 * 1024, 0);
312 lprintf(CTDL_EMERG, "cdb_*: set_cachesize: %s\n",
314 dbenv->close(dbenv, 0);
318 if ((ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT))) {
319 lprintf(CTDL_EMERG, "cdb_*: set_lk_detect: %s\n",
321 dbenv->close(dbenv, 0);
325 flags = DB_CREATE | DB_INIT_MPOOL | DB_PRIVATE | DB_INIT_TXN | DB_INIT_LOCK | DB_THREAD | DB_RECOVER;
326 lprintf(CTDL_DEBUG, "dbenv->open(dbenv, %s, %d, 0)\n", ctdl_data_dir, flags);
327 ret = dbenv->open(dbenv, ctdl_data_dir, flags, 0);
328 if (ret == DB_RUNRECOVERY) {
329 lprintf(CTDL_ALERT, "dbenv->open: %s\n", db_strerror(ret));
330 lprintf(CTDL_ALERT, "Attempting recovery...\n");
332 ret = dbenv->open(dbenv, ctdl_data_dir, flags, 0);
334 if (ret == DB_RUNRECOVERY) {
335 lprintf(CTDL_ALERT, "dbenv->open: %s\n", db_strerror(ret));
336 lprintf(CTDL_ALERT, "Attempting catastrophic recovery...\n");
337 flags &= ~DB_RECOVER;
338 flags |= DB_RECOVER_FATAL;
339 ret = dbenv->open(dbenv, ctdl_data_dir, flags, 0);
342 lprintf(CTDL_DEBUG, "dbenv->open: %s\n", db_strerror(ret));
343 dbenv->close(dbenv, 0);
347 lprintf(CTDL_INFO, "Starting up DB\n");
349 for (i = 0; i < MAXCDB; ++i) {
351 /* Create a database handle */
352 ret = db_create(&dbp[i], dbenv, 0);
354 lprintf(CTDL_DEBUG, "db_create: %s\n",
360 /* Arbitrary names for our tables -- we reference them by
361 * number, so we don't have string names for them.
363 snprintf(dbfilename, sizeof dbfilename, "cdb.%02x", i);
365 ret = dbp[i]->open(dbp[i],
370 DB_CREATE | DB_AUTO_COMMIT | DB_THREAD,
373 lprintf(CTDL_EMERG, "db_open[%d]: %s\n", i,
382 /* Make sure we own all the files, because in a few milliseconds
383 * we're going to drop root privs.
385 void cdb_chmod_data(void) {
388 char filename[PATH_MAX];
390 dp = opendir(ctdl_data_dir);
392 while (d = readdir(dp), d != NULL) {
393 if (d->d_name[0] != '.') {
394 snprintf(filename, sizeof filename,
395 "%s/%s", ctdl_data_dir, d->d_name);
396 lprintf(9, "chmod(%s, 0600) returned %d\n",
397 filename, chmod(filename, 0600)
399 lprintf(9, "chown(%s, CTDLUID, -1) returned %d\n",
400 filename, chown(filename, CTDLUID, (-1))
407 lprintf(CTDL_DEBUG, "open_databases() finished\n");
409 CtdlRegisterProtoHook(cmd_cull, "CULL", "Cull database logs");
414 * Close all of the db database files we've opened. This can be done
415 * in a loop, since it's just a bunch of closes.
417 void close_databases(void)
422 ctdl_thread_internal_free_tsd();
424 if ((ret = dbenv->txn_checkpoint(dbenv, 0, 0, 0))) {
426 "txn_checkpoint: %s\n", db_strerror(ret));
429 /* print some statistics... */
431 dbenv->lock_stat_print(dbenv, DB_STAT_ALL);
434 /* close the tables */
435 for (a = 0; a < MAXCDB; ++a) {
436 lprintf(CTDL_INFO, "Closing database %d\n", a);
437 ret = dbp[a]->close(dbp[a], 0);
440 "db_close: %s\n", db_strerror(ret));
445 /* Close the handle. */
446 ret = dbenv->close(dbenv, 0);
449 "DBENV->close: %s\n", db_strerror(ret));
455 * Compression functions only used if we have zlib
459 void cdb_decompress_if_necessary(struct cdbdata *cdb)
461 static int magic = COMPRESS_MAGIC;
462 struct CtdlCompressHeader zheader;
463 char *uncompressed_data;
464 char *compressed_data;
465 uLongf destLen, sourceLen;
469 if (cdb->ptr == NULL)
471 if (memcmp(cdb->ptr, &magic, sizeof(magic)))
474 /* At this point we know we're looking at a compressed item. */
475 memcpy(&zheader, cdb->ptr, sizeof(struct CtdlCompressHeader));
477 compressed_data = cdb->ptr;
478 compressed_data += sizeof(struct CtdlCompressHeader);
480 sourceLen = (uLongf) zheader.compressed_len;
481 destLen = (uLongf) zheader.uncompressed_len;
482 uncompressed_data = malloc(zheader.uncompressed_len);
484 if (uncompress((Bytef *) uncompressed_data,
485 (uLongf *) & destLen,
486 (const Bytef *) compressed_data,
487 (uLong) sourceLen) != Z_OK) {
488 lprintf(CTDL_EMERG, "uncompress() error\n");
493 cdb->len = (size_t) destLen;
494 cdb->ptr = uncompressed_data;
497 #endif /* HAVE_ZLIB */
501 * Store a piece of data. Returns 0 if the operation was successful. If a
502 * key already exists it should be overwritten.
504 int cdb_store(int cdb, void *ckey, int ckeylen, void *cdata, int cdatalen)
512 struct CtdlCompressHeader zheader;
513 char *compressed_data = NULL;
515 size_t buffer_len = 0;
519 memset(&dkey, 0, sizeof(DBT));
520 memset(&ddata, 0, sizeof(DBT));
523 ddata.size = cdatalen;
527 /* Only compress Visit records. Everything else is uncompressed. */
528 if (cdb == CDB_VISIT) {
530 zheader.magic = COMPRESS_MAGIC;
531 zheader.uncompressed_len = cdatalen;
532 buffer_len = ((cdatalen * 101) / 100) + 100
533 + sizeof(struct CtdlCompressHeader);
534 destLen = (uLongf) buffer_len;
535 compressed_data = malloc(buffer_len);
536 if (compress2((Bytef *) (compressed_data +
538 CtdlCompressHeader)),
539 &destLen, (Bytef *) cdata, (uLongf) cdatalen,
541 lprintf(CTDL_EMERG, "compress2() error\n");
544 zheader.compressed_len = (size_t) destLen;
545 memcpy(compressed_data, &zheader,
546 sizeof(struct CtdlCompressHeader));
547 ddata.size = (size_t) (sizeof(struct CtdlCompressHeader) +
548 zheader.compressed_len);
549 ddata.data = compressed_data;
554 ret = dbp[cdb]->put(dbp[cdb], /* db */
555 MYTID, /* transaction ID */
560 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n", cdb,
566 free(compressed_data);
571 bailIfCursor(MYCURSORS,
572 "attempt to write during r/o cursor");
577 if ((ret = dbp[cdb]->put(dbp[cdb], /* db */
578 tid, /* transaction ID */
582 if (ret == DB_LOCK_DEADLOCK) {
586 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n",
587 cdb, db_strerror(ret));
594 free(compressed_data);
603 * Delete a piece of data. Returns 0 if the operation was successful.
605 int cdb_delete(int cdb, void *key, int keylen)
612 memset(&dkey, 0, sizeof dkey);
617 ret = dbp[cdb]->del(dbp[cdb], MYTID, &dkey, 0);
619 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n", cdb,
621 if (ret != DB_NOTFOUND)
625 bailIfCursor(MYCURSORS,
626 "attempt to delete during r/o cursor");
631 if ((ret = dbp[cdb]->del(dbp[cdb], tid, &dkey, 0))
632 && ret != DB_NOTFOUND) {
633 if (ret == DB_LOCK_DEADLOCK) {
637 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n",
638 cdb, db_strerror(ret));
648 static DBC *localcursor(int cdb)
653 if (MYCURSORS[cdb] == NULL)
654 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &curs, 0);
657 MYCURSORS[cdb]->c_dup(MYCURSORS[cdb], &curs,
661 lprintf(CTDL_EMERG, "localcursor: %s\n", db_strerror(ret));
670 * Fetch a piece of data. If not found, returns NULL. Otherwise, it returns
671 * a struct cdbdata which it is the caller's responsibility to free later on
672 * using the cdb_free() routine.
674 struct cdbdata *cdb_fetch(int cdb, void *key, int keylen)
677 struct cdbdata *tempcdb;
681 memset(&dkey, 0, sizeof(DBT));
686 memset(&dret, 0, sizeof(DBT));
687 dret.flags = DB_DBT_MALLOC;
688 ret = dbp[cdb]->get(dbp[cdb], MYTID, &dkey, &dret, 0);
693 memset(&dret, 0, sizeof(DBT));
694 dret.flags = DB_DBT_MALLOC;
696 curs = localcursor(cdb);
698 ret = curs->c_get(curs, &dkey, &dret, DB_SET);
701 while (ret == DB_LOCK_DEADLOCK);
705 if ((ret != 0) && (ret != DB_NOTFOUND)) {
706 lprintf(CTDL_EMERG, "cdb_fetch(%d): %s\n", cdb,
713 tempcdb = (struct cdbdata *) malloc(sizeof(struct cdbdata));
715 if (tempcdb == NULL) {
717 "cdb_fetch: Cannot allocate memory for tempcdb\n");
721 tempcdb->len = dret.size;
722 tempcdb->ptr = dret.data;
724 cdb_decompress_if_necessary(tempcdb);
731 * Free a cdbdata item.
733 * Note that we only free the 'ptr' portion if it is not NULL. This allows
734 * other code to assume ownership of that memory simply by storing the
735 * pointer elsewhere and then setting 'ptr' to NULL. cdb_free() will then
738 void cdb_free(struct cdbdata *cdb)
746 void cdb_close_cursor(int cdb)
748 if (MYCURSORS[cdb] != NULL)
749 cclose(MYCURSORS[cdb]);
751 MYCURSORS[cdb] = NULL;
755 * Prepare for a sequential search of an entire database.
756 * (There is guaranteed to be no more than one traversal in
757 * progress per thread at any given time.)
759 void cdb_rewind(int cdb)
763 if (MYCURSORS[cdb] != NULL) {
765 "cdb_rewind: must close cursor on database %d before reopening.\n",
768 /* cclose(MYCURSORS[cdb]); */
772 * Now initialize the cursor
774 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &MYCURSORS[cdb], 0);
776 lprintf(CTDL_EMERG, "cdb_rewind: db_cursor: %s\n",
784 * Fetch the next item in a sequential search. Returns a pointer to a
785 * cdbdata structure, or NULL if we've hit the end.
787 struct cdbdata *cdb_next_item(int cdb)
790 struct cdbdata *cdbret;
793 /* Initialize the key/data pair so the flags aren't set. */
794 memset(&key, 0, sizeof(key));
795 memset(&data, 0, sizeof(data));
796 data.flags = DB_DBT_MALLOC;
798 ret = MYCURSORS[cdb]->c_get(MYCURSORS[cdb], &key, &data, DB_NEXT);
801 if (ret != DB_NOTFOUND) {
802 lprintf(CTDL_EMERG, "cdb_next_item(%d): %s\n",
803 cdb, db_strerror(ret));
806 cclose(MYCURSORS[cdb]);
807 MYCURSORS[cdb] = NULL;
808 return NULL; /* presumably, end of file */
811 cdbret = (struct cdbdata *) malloc(sizeof(struct cdbdata));
812 cdbret->len = data.size;
813 cdbret->ptr = data.data;
815 cdb_decompress_if_necessary(cdbret);
824 * Transaction-based stuff. I'm writing this as I bake cookies...
827 void cdb_begin_transaction(void)
830 bailIfCursor(MYCURSORS,
831 "can't begin transaction during r/o cursor");
835 "cdb_begin_transaction: ERROR: nested transaction\n");
842 void cdb_end_transaction(void)
846 for (i = 0; i < MAXCDB; i++)
847 if (MYCURSORS[i] != NULL) {
848 lprintf(CTDL_WARNING,
849 "cdb_end_transaction: WARNING: cursor %d still open at transaction end\n",
851 cclose(MYCURSORS[i]);
857 "cdb_end_transaction: ERROR: txcommit(NULL) !!\n");
866 * Truncate (delete every record)
868 void cdb_trunc(int cdb)
876 "cdb_trunc must not be called in a transaction.\n");
879 bailIfCursor(MYCURSORS,
880 "attempt to write during r/o cursor");
885 if ((ret = dbp[cdb]->truncate(dbp[cdb], /* db */
886 NULL, /* transaction ID */
887 &count, /* #rows deleted */
889 if (ret == DB_LOCK_DEADLOCK) {
894 "cdb_truncate(%d): %s\n", cdb,