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 static void cdb_checkpoint(void)
286 static time_t last_run = 0L;
288 /* Only do a checkpoint once per minute. */
289 if ((time(NULL) - last_run) < 60L) {
292 last_run = time(NULL);
294 lprintf(CTDL_DEBUG, "-- db checkpoint --\n");
295 ret = dbenv->txn_checkpoint(dbenv,
296 MAX_CHECKPOINT_KBYTES,
297 MAX_CHECKPOINT_MINUTES, 0);
300 lprintf(CTDL_EMERG, "cdb_checkpoint: txn_checkpoint: %s\n",
305 /* After a successful checkpoint, we can cull the unused logs */
306 if (config.c_auto_cull) {
313 * Main loop for the checkpoint thread.
315 void *checkpoint_thread(void *arg) {
316 struct CitContext checkpointCC;
318 lprintf(CTDL_DEBUG, "checkpoint_thread() initializing\n");
320 memset(&checkpointCC, 0, sizeof(struct CitContext));
321 checkpointCC.internal_pgm = 1;
322 checkpointCC.cs_pid = 0;
323 pthread_setspecific(MyConKey, (void *)&checkpointCC );
327 while (!time_to_die) {
332 lprintf(CTDL_DEBUG, "checkpoint_thread() exiting\n");
337 * Open the various databases we'll be using. Any database which
338 * does not exist should be created. Note that we don't need a
339 * critical section here, because there aren't any active threads
340 * manipulating the database yet.
342 void open_databases(void)
346 char dbfilename[SIZ];
349 lprintf(CTDL_DEBUG, "cdb_*: open_databases() starting\n");
350 lprintf(CTDL_DEBUG, "Compiled db: %s\n", DB_VERSION_STRING);
351 lprintf(CTDL_INFO, " Linked db: %s\n",
352 db_version(NULL, NULL, NULL));
354 lprintf(CTDL_INFO, "Linked zlib: %s\n", zlibVersion());
358 * Silently try to create the database subdirectory. If it's
359 * already there, no problem.
361 mkdir(ctdl_data_dir, 0700);
362 chmod(ctdl_data_dir, 0700);
363 chown(ctdl_data_dir, CTDLUID, (-1));
365 lprintf(CTDL_DEBUG, "cdb_*: Setting up DB environment\n");
366 db_env_set_func_yield(sched_yield);
367 ret = db_env_create(&dbenv, 0);
369 lprintf(CTDL_EMERG, "cdb_*: db_env_create: %s\n",
373 dbenv->set_errpfx(dbenv, "citserver");
374 dbenv->set_paniccall(dbenv, dbpanic);
375 dbenv->set_errcall(dbenv, cdb_verbose_err);
376 dbenv->set_errpfx(dbenv, "ctdl");
377 #if (DB_VERSION_MAJOR == 4) && (DB_VERSION_MINOR >= 3)
378 dbenv->set_msgcall(dbenv, cdb_verbose_log);
380 dbenv->set_verbose(dbenv, DB_VERB_DEADLOCK, 1);
381 dbenv->set_verbose(dbenv, DB_VERB_RECOVERY, 1);
384 * We want to specify the shared memory buffer pool cachesize,
385 * but everything else is the default.
387 ret = dbenv->set_cachesize(dbenv, 0, 64 * 1024, 0);
389 lprintf(CTDL_EMERG, "cdb_*: set_cachesize: %s\n",
391 dbenv->close(dbenv, 0);
395 if ((ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT))) {
396 lprintf(CTDL_EMERG, "cdb_*: set_lk_detect: %s\n",
398 dbenv->close(dbenv, 0);
403 DB_CREATE | DB_RECOVER | DB_INIT_MPOOL |
404 DB_PRIVATE | DB_INIT_TXN | DB_INIT_LOCK | DB_THREAD;
405 lprintf(CTDL_DEBUG, "dbenv->open(dbenv, %s, %d, 0)\n",
406 ctdl_data_dir, flags);
407 ret = dbenv->open(dbenv, ctdl_data_dir, flags, 0);
409 lprintf(CTDL_DEBUG, "cdb_*: dbenv->open: %s\n",
411 dbenv->close(dbenv, 0);
415 lprintf(CTDL_INFO, "cdb_*: Starting up DB\n");
417 for (i = 0; i < MAXCDB; ++i) {
419 /* Create a database handle */
420 ret = db_create(&dbp[i], dbenv, 0);
422 lprintf(CTDL_DEBUG, "cdb_*: db_create: %s\n",
428 /* Arbitrary names for our tables -- we reference them by
429 * number, so we don't have string names for them.
431 snprintf(dbfilename, sizeof dbfilename, "cdb.%02x", i);
433 ret = dbp[i]->open(dbp[i],
438 DB_CREATE | DB_AUTO_COMMIT | DB_THREAD,
441 lprintf(CTDL_EMERG, "cdb_*: db_open[%d]: %s\n", i,
447 if ((ret = pthread_key_create(&tsdkey, dest_tsd))) {
448 lprintf(CTDL_EMERG, "cdb_*: pthread_key_create: %s\n",
455 CtdlRegisterMaintenanceThread ("checkpoint", checkpoint_thread);
459 /* Make sure we own all the files, because in a few milliseconds
460 * we're going to drop root privs.
462 void cdb_chmod_data(void) {
465 char filename[PATH_MAX];
467 dp = opendir(ctdl_data_dir);
469 while (d = readdir(dp), d != NULL) {
470 if (d->d_name[0] != '.') {
471 snprintf(filename, sizeof filename,
472 "%s/%s", ctdl_data_dir, d->d_name);
473 lprintf(9, "chmod(%s, 0600) returned %d\n",
474 filename, chmod(filename, 0600)
476 lprintf(9, "chown(%s, CTDLUID, -1) returned %d\n",
477 filename, chown(filename, CTDLUID, (-1))
484 lprintf(CTDL_DEBUG, "cdb_*: open_databases() finished\n");
486 CtdlRegisterProtoHook(cmd_cull, "CULL", "Cull database logs");
491 * Close all of the db database files we've opened. This can be done
492 * in a loop, since it's just a bunch of closes.
494 void close_databases(void)
501 if ((ret = dbenv->txn_checkpoint(dbenv, 0, 0, 0))) {
503 "cdb_*: txn_checkpoint: %s\n", db_strerror(ret));
506 /* print some statistics... */
507 dbenv->lock_stat_print(dbenv, DB_STAT_ALL);
509 /* close the tables */
510 for (a = 0; a < MAXCDB; ++a) {
511 lprintf(CTDL_INFO, "cdb_*: Closing database %d\n", a);
512 ret = dbp[a]->close(dbp[a], 0);
515 "cdb_*: db_close: %s\n", db_strerror(ret));
520 /* Close the handle. */
521 ret = dbenv->close(dbenv, 0);
524 "cdb_*: DBENV->close: %s\n", db_strerror(ret));
530 * Compression functions only used if we have zlib
534 void cdb_decompress_if_necessary(struct cdbdata *cdb)
536 static int magic = COMPRESS_MAGIC;
537 struct CtdlCompressHeader zheader;
538 char *uncompressed_data;
539 char *compressed_data;
540 uLongf destLen, sourceLen;
544 if (cdb->ptr == NULL)
546 if (memcmp(cdb->ptr, &magic, sizeof(magic)))
549 /* At this point we know we're looking at a compressed item. */
550 memcpy(&zheader, cdb->ptr, sizeof(struct CtdlCompressHeader));
552 compressed_data = cdb->ptr;
553 compressed_data += sizeof(struct CtdlCompressHeader);
555 sourceLen = (uLongf) zheader.compressed_len;
556 destLen = (uLongf) zheader.uncompressed_len;
557 uncompressed_data = malloc(zheader.uncompressed_len);
559 if (uncompress((Bytef *) uncompressed_data,
560 (uLongf *) & destLen,
561 (const Bytef *) compressed_data,
562 (uLong) sourceLen) != Z_OK) {
563 lprintf(CTDL_EMERG, "uncompress() error\n");
568 cdb->len = (size_t) destLen;
569 cdb->ptr = uncompressed_data;
572 #endif /* HAVE_ZLIB */
576 * Store a piece of data. Returns 0 if the operation was successful. If a
577 * key already exists it should be overwritten.
579 int cdb_store(int cdb, void *ckey, int ckeylen, void *cdata, int cdatalen)
587 struct CtdlCompressHeader zheader;
588 char *compressed_data = NULL;
590 size_t buffer_len = 0;
594 memset(&dkey, 0, sizeof(DBT));
595 memset(&ddata, 0, sizeof(DBT));
598 ddata.size = cdatalen;
602 /* Only compress Visit records. Everything else is uncompressed. */
603 if (cdb == CDB_VISIT) {
605 zheader.magic = COMPRESS_MAGIC;
606 zheader.uncompressed_len = cdatalen;
607 buffer_len = ((cdatalen * 101) / 100) + 100
608 + sizeof(struct CtdlCompressHeader);
609 destLen = (uLongf) buffer_len;
610 compressed_data = malloc(buffer_len);
611 if (compress2((Bytef *) (compressed_data +
613 CtdlCompressHeader)),
614 &destLen, (Bytef *) cdata, (uLongf) cdatalen,
616 lprintf(CTDL_EMERG, "compress2() error\n");
619 zheader.compressed_len = (size_t) destLen;
620 memcpy(compressed_data, &zheader,
621 sizeof(struct CtdlCompressHeader));
622 ddata.size = (size_t) (sizeof(struct CtdlCompressHeader) +
623 zheader.compressed_len);
624 ddata.data = compressed_data;
629 ret = dbp[cdb]->put(dbp[cdb], /* db */
630 MYTID, /* transaction ID */
635 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n", cdb,
641 free(compressed_data);
646 bailIfCursor(MYCURSORS,
647 "attempt to write during r/o cursor");
652 if ((ret = dbp[cdb]->put(dbp[cdb], /* db */
653 tid, /* transaction ID */
657 if (ret == DB_LOCK_DEADLOCK) {
661 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n",
662 cdb, db_strerror(ret));
669 free(compressed_data);
678 * Delete a piece of data. Returns 0 if the operation was successful.
680 int cdb_delete(int cdb, void *key, int keylen)
687 memset(&dkey, 0, sizeof dkey);
692 ret = dbp[cdb]->del(dbp[cdb], MYTID, &dkey, 0);
694 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n", cdb,
696 if (ret != DB_NOTFOUND)
700 bailIfCursor(MYCURSORS,
701 "attempt to delete during r/o cursor");
706 if ((ret = dbp[cdb]->del(dbp[cdb], tid, &dkey, 0))
707 && ret != DB_NOTFOUND) {
708 if (ret == DB_LOCK_DEADLOCK) {
712 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n",
713 cdb, db_strerror(ret));
723 static DBC *localcursor(int cdb)
728 if (MYCURSORS[cdb] == NULL)
729 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &curs, 0);
732 MYCURSORS[cdb]->c_dup(MYCURSORS[cdb], &curs,
736 lprintf(CTDL_EMERG, "localcursor: %s\n", db_strerror(ret));
745 * Fetch a piece of data. If not found, returns NULL. Otherwise, it returns
746 * a struct cdbdata which it is the caller's responsibility to free later on
747 * using the cdb_free() routine.
749 struct cdbdata *cdb_fetch(int cdb, void *key, int keylen)
752 struct cdbdata *tempcdb;
756 memset(&dkey, 0, sizeof(DBT));
761 memset(&dret, 0, sizeof(DBT));
762 dret.flags = DB_DBT_MALLOC;
763 ret = dbp[cdb]->get(dbp[cdb], MYTID, &dkey, &dret, 0);
768 memset(&dret, 0, sizeof(DBT));
769 dret.flags = DB_DBT_MALLOC;
771 curs = localcursor(cdb);
773 ret = curs->c_get(curs, &dkey, &dret, DB_SET);
776 while (ret == DB_LOCK_DEADLOCK);
780 if ((ret != 0) && (ret != DB_NOTFOUND)) {
781 lprintf(CTDL_EMERG, "cdb_fetch(%d): %s\n", cdb,
788 tempcdb = (struct cdbdata *) malloc(sizeof(struct cdbdata));
790 if (tempcdb == NULL) {
792 "cdb_fetch: Cannot allocate memory for tempcdb\n");
796 tempcdb->len = dret.size;
797 tempcdb->ptr = dret.data;
799 cdb_decompress_if_necessary(tempcdb);
806 * Free a cdbdata item.
808 * Note that we only free the 'ptr' portion if it is not NULL. This allows
809 * other code to assume ownership of that memory simply by storing the
810 * pointer elsewhere and then setting 'ptr' to NULL. cdb_free() will then
813 void cdb_free(struct cdbdata *cdb)
821 void cdb_close_cursor(int cdb)
823 if (MYCURSORS[cdb] != NULL)
824 cclose(MYCURSORS[cdb]);
826 MYCURSORS[cdb] = NULL;
830 * Prepare for a sequential search of an entire database.
831 * (There is guaranteed to be no more than one traversal in
832 * progress per thread at any given time.)
834 void cdb_rewind(int cdb)
838 if (MYCURSORS[cdb] != NULL) {
840 "cdb_rewind: must close cursor on database %d before reopening.\n",
843 /* cclose(MYCURSORS[cdb]); */
847 * Now initialize the cursor
849 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &MYCURSORS[cdb], 0);
851 lprintf(CTDL_EMERG, "cdb_rewind: db_cursor: %s\n",
859 * Fetch the next item in a sequential search. Returns a pointer to a
860 * cdbdata structure, or NULL if we've hit the end.
862 struct cdbdata *cdb_next_item(int cdb)
865 struct cdbdata *cdbret;
868 /* Initialize the key/data pair so the flags aren't set. */
869 memset(&key, 0, sizeof(key));
870 memset(&data, 0, sizeof(data));
871 data.flags = DB_DBT_MALLOC;
873 ret = MYCURSORS[cdb]->c_get(MYCURSORS[cdb], &key, &data, DB_NEXT);
876 if (ret != DB_NOTFOUND) {
877 lprintf(CTDL_EMERG, "cdb_next_item(%d): %s\n",
878 cdb, db_strerror(ret));
881 cclose(MYCURSORS[cdb]);
882 MYCURSORS[cdb] = NULL;
883 return NULL; /* presumably, end of file */
886 cdbret = (struct cdbdata *) malloc(sizeof(struct cdbdata));
887 cdbret->len = data.size;
888 cdbret->ptr = data.data;
890 cdb_decompress_if_necessary(cdbret);
899 * Transaction-based stuff. I'm writing this as I bake cookies...
902 void cdb_begin_transaction(void)
905 bailIfCursor(MYCURSORS,
906 "can't begin transaction during r/o cursor");
910 "cdb_begin_transaction: ERROR: nested transaction\n");
917 void cdb_end_transaction(void)
921 for (i = 0; i < MAXCDB; i++)
922 if (MYCURSORS[i] != NULL) {
923 lprintf(CTDL_WARNING,
924 "cdb_end_transaction: WARNING: cursor %d still open at transaction end\n",
926 cclose(MYCURSORS[i]);
932 "cdb_end_transaction: ERROR: txcommit(NULL) !!\n");
941 * Truncate (delete every record)
943 void cdb_trunc(int cdb)
951 "cdb_trunc must not be called in a transaction.\n");
954 bailIfCursor(MYCURSORS,
955 "attempt to write during r/o cursor");
960 if ((ret = dbp[cdb]->truncate(dbp[cdb], /* db */
961 NULL, /* transaction ID */
962 &count, /* #rows deleted */
964 if (ret == DB_LOCK_DEADLOCK) {
969 "cdb_truncate(%d): %s\n", cdb,