4 * Sleepycat (Berkeley) DB driver for Citadel/UX
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 /*****************************************************************************/
32 #include <sys/types.h>
38 #elif defined(HAVE_DB4_DB_H)
41 #error Neither <db.h> nor <db4/db.h> was found by configure. Install db4-devel.
45 #if DB_VERSION_MAJOR < 4 || DB_VERSION_MINOR < 1
46 #error Citadel requires Berkeley DB v4.1 or newer. Please upgrade.
53 #include "serv_extensions.h"
54 #include "citserver.h"
57 #include "sysdep_decls.h"
59 static DB *dbp[MAXCDB]; /* One DB handle for each Citadel database */
60 static DB_ENV *dbenv; /* The DB environment (global) */
62 struct cdbtsd { /* Thread-specific DB stuff */
63 DB_TXN *tid; /* Transaction handle */
64 DBC *cursors[MAXCDB]; /* Cursors, for traversals... */
71 static pthread_key_t tsdkey;
73 #define MYCURSORS (((struct cdbtsd*)pthread_getspecific(tsdkey))->cursors)
74 #define MYTID (((struct cdbtsd*)pthread_getspecific(tsdkey))->tid)
76 /* just a little helper function */
77 static void txabort(DB_TXN *tid) {
80 ret = tid->abort(tid);
83 lprintf(CTDL_EMERG, "cdb_*: txn_abort: %s\n", db_strerror(ret));
88 /* this one is even more helpful than the last. */
89 static void txcommit(DB_TXN *tid) {
92 ret = tid->commit(tid, 0);
95 lprintf(CTDL_EMERG, "cdb_*: txn_commit: %s\n", db_strerror(ret));
100 /* are you sensing a pattern yet? */
101 static void txbegin(DB_TXN **tid) {
104 ret = dbenv->txn_begin(dbenv, NULL, tid, 0);
107 lprintf(CTDL_EMERG, "cdb_*: txn_begin: %s\n", db_strerror(ret));
112 static void dbpanic(DB_ENV* env, int errval)
114 lprintf(CTDL_EMERG, "cdb_*: Berkeley DB panic: %d\n", errval);
117 static void cclose(DBC *cursor) {
120 if ((ret = cursor->c_close(cursor))) {
121 lprintf(CTDL_EMERG, "cdb_*: c_close: %s\n", db_strerror(ret));
126 static void bailIfCursor(DBC **cursors, const char *msg)
130 for (i = 0; i < MAXCDB; i++)
131 if (cursors[i] != NULL)
133 lprintf(CTDL_EMERG, "cdb_*: cursor still in progress on cdb %d: %s\n", i, msg);
138 static void check_handles(void *arg) {
140 struct cdbtsd *tsd = (struct cdbtsd *)arg;
142 bailIfCursor(tsd->cursors, "in check_handles");
144 if (tsd->tid != NULL) {
145 lprintf(CTDL_EMERG, "cdb_*: transaction still in progress!");
151 static void dest_tsd(void *arg) {
159 * Ensure that we have a key for thread-specific data. We don't
160 * put anything in here that Citadel cares about; this is just database
161 * related stuff like cursors and transactions.
163 * This should be called immediately after startup by any thread which wants
164 * to use database calls, except for whatever thread calls open_databases.
166 void cdb_allocate_tsd(void) {
169 if (pthread_getspecific(tsdkey) != NULL)
172 tsd = mallok(sizeof(struct cdbtsd));
176 memset(tsd->cursors, 0, sizeof tsd->cursors);
177 pthread_setspecific(tsdkey, tsd);
180 void cdb_free_tsd(void) {
181 dest_tsd(pthread_getspecific(tsdkey));
182 pthread_setspecific(tsdkey, NULL);
185 void cdb_check_handles(void) {
186 check_handles(pthread_getspecific(tsdkey));
191 * Reclaim unused space in the databases. We need to do each one of
192 * these discretely, rather than in a loop.
194 * This is a stub function in the Sleepycat DB backend, because there is no
195 * such API call available.
197 void defrag_databases(void)
204 * Cull the database logs
206 static void cdb_cull_logs(void) {
212 lprintf(CTDL_INFO, "Database log file cull started.\n");
216 /* Get the list of names. */
217 if ((ret = dbenv->log_archive(dbenv, &list, flags)) != 0) {
218 lprintf(CTDL_ERR, "cdb_cull_logs: %s\n", db_strerror(ret));
222 /* Print the list of names. */
224 for (file = list; *file != NULL; ++file) {
225 lprintf(CTDL_DEBUG, "Deleting log: %s\n", *file);
228 snprintf(errmsg, sizeof(errmsg),
229 " ** ERROR **\n \n \n "
230 "Citadel was unable to delete the "
231 "database log file '%s' because of the "
232 "following error:\n \n %s\n \n"
233 " This log file is no longer in use "
234 "and may be safely deleted.\n",
237 aide_message(errmsg);
243 lprintf(CTDL_INFO, "Database log file cull ended.\n");
248 * Request a checkpoint of the database.
250 static void cdb_checkpoint(void) {
252 static time_t last_cull = 0L;
254 ret = dbenv->txn_checkpoint(dbenv,
255 MAX_CHECKPOINT_KBYTES,
256 MAX_CHECKPOINT_MINUTES,
260 lprintf(CTDL_EMERG, "cdb_checkpoint: txn_checkpoint: %s\n",
265 /* Cull the logs if we haven't done so for 24 hours */
266 if ((time(NULL) - last_cull) > 86400L) {
267 last_cull = time(NULL);
274 * Open the various databases we'll be using. Any database which
275 * does not exist should be created. Note that we don't need an S_DATABASE
276 * critical section here, because there aren't any active threads manipulating
277 * the database yet -- and besides, it causes problems on BSDI.
279 void open_databases(void)
283 char dbfilename[SIZ];
285 char dbdirname[PATH_MAX];
287 getcwd(dbdirname, sizeof dbdirname);
288 strcat(dbdirname, "/data");
290 lprintf(CTDL_DEBUG, "cdb_*: open_databases() starting\n");
291 lprintf(CTDL_DEBUG, "Compiled db: %s\n", DB_VERSION_STRING);
292 lprintf(CTDL_INFO, " Linked db: %s\n", db_version(NULL, NULL, NULL));
294 lprintf(CTDL_INFO, "Linked zlib: %s\n", zlibVersion());
298 * Silently try to create the database subdirectory. If it's
299 * already there, no problem.
301 mkdir(dbdirname, 0700);
302 chmod(dbdirname, 0700);
304 lprintf(CTDL_DEBUG, "cdb_*: Setting up DB environment\n");
305 db_env_set_func_yield(sched_yield);
306 ret = db_env_create(&dbenv, 0);
308 lprintf(CTDL_EMERG, "cdb_*: db_env_create: %s\n", db_strerror(ret));
311 dbenv->set_errpfx(dbenv, "citserver");
312 dbenv->set_paniccall(dbenv, dbpanic);
315 * We want to specify the shared memory buffer pool cachesize,
316 * but everything else is the default.
318 ret = dbenv->set_cachesize(dbenv, 0, 64 * 1024, 0);
320 lprintf(CTDL_EMERG, "cdb_*: set_cachesize: %s\n", db_strerror(ret));
321 dbenv->close(dbenv, 0);
325 if ((ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT))) {
326 lprintf(CTDL_EMERG, "cdb_*: set_lk_detect: %s\n", db_strerror(ret));
327 dbenv->close(dbenv, 0);
331 flags = DB_CREATE|DB_RECOVER|DB_INIT_MPOOL|DB_PRIVATE|DB_INIT_TXN|
332 DB_INIT_LOCK|DB_THREAD;
333 lprintf(CTDL_DEBUG, "dbenv->open(dbenv, %s, %d, 0)\n", dbdirname, flags);
334 ret = dbenv->open(dbenv, dbdirname, flags, 0);
336 lprintf(CTDL_DEBUG, "cdb_*: dbenv->open: %s\n", db_strerror(ret));
337 dbenv->close(dbenv, 0);
341 lprintf(CTDL_INFO, "cdb_*: Starting up DB\n");
343 for (i = 0; i < MAXCDB; ++i) {
345 /* Create a database handle */
346 ret = db_create(&dbp[i], dbenv, 0);
348 lprintf(CTDL_DEBUG, "cdb_*: db_create: %s\n", db_strerror(ret));
353 /* Arbitrary names for our tables -- we reference them by
354 * number, so we don't have string names for them.
356 snprintf(dbfilename, sizeof dbfilename, "cdb.%02x", i);
358 ret = dbp[i]->open(dbp[i],
368 lprintf(CTDL_EMERG, "cdb_*: db_open[%d]: %s\n", i, db_strerror(ret));
373 if ((ret = pthread_key_create(&tsdkey, dest_tsd))) {
374 lprintf(CTDL_EMERG, "cdb_*: pthread_key_create: %s\n", strerror(ret));
379 CtdlRegisterSessionHook(cdb_checkpoint, EVT_TIMER);
380 lprintf(CTDL_DEBUG, "cdb_*: open_databases() finished\n");
385 * Close all of the db database files we've opened. This can be done
386 * in a loop, since it's just a bunch of closes.
388 void close_databases(void)
395 if ((ret = dbenv->txn_checkpoint(dbenv, 0, 0, 0))) {
396 lprintf(CTDL_EMERG, "cdb_*: txn_checkpoint: %s\n", db_strerror(ret));
400 for (a = 0; a < MAXCDB; ++a) {
401 lprintf(CTDL_INFO, "cdb_*: Closing database %d\n", a);
402 ret = dbp[a]->close(dbp[a], 0);
404 lprintf(CTDL_EMERG, "cdb_*: db_close: %s\n", db_strerror(ret));
410 /* Close the handle. */
411 ret = dbenv->close(dbenv, 0);
413 lprintf(CTDL_EMERG, "cdb_*: DBENV->close: %s\n", db_strerror(ret));
420 * Compression functions only used if we have zlib
424 void cdb_decompress_if_necessary(struct cdbdata *cdb) {
425 static int magic = COMPRESS_MAGIC;
426 struct CtdlCompressHeader zheader;
427 char *uncompressed_data;
428 char *compressed_data;
429 uLongf destLen, sourceLen;
431 if (cdb == NULL) return;
432 if (cdb->ptr == NULL) return;
433 if (memcmp(cdb->ptr, &magic, sizeof(magic))) return;
435 /* At this point we know we're looking at a compressed item. */
436 memcpy(&zheader, cdb->ptr, sizeof(struct CtdlCompressHeader));
438 compressed_data = cdb->ptr;
439 compressed_data += sizeof(struct CtdlCompressHeader);
441 sourceLen = (uLongf) zheader.compressed_len;
442 destLen = (uLongf) zheader.uncompressed_len;
443 uncompressed_data = mallok(zheader.uncompressed_len);
445 if (uncompress( (Bytef *) uncompressed_data,
450 lprintf(CTDL_EMERG, "uncompress() error\n");
455 cdb->len = (size_t) destLen;
456 cdb->ptr = uncompressed_data;
459 #endif /* HAVE_ZLIB */
463 * Store a piece of data. Returns 0 if the operation was successful. If a
464 * key already exists it should be overwritten.
466 int cdb_store(int cdb,
467 void *ckey, int ckeylen,
468 void *cdata, int cdatalen)
476 struct CtdlCompressHeader zheader;
477 char *compressed_data = NULL;
483 memset(&dkey, 0, sizeof(DBT));
484 memset(&ddata, 0, sizeof(DBT));
487 ddata.size = cdatalen;
491 /* Only compress Visit records. Everything else is uncompressed. */
492 if (cdb == CDB_VISIT) {
494 zheader.magic = COMPRESS_MAGIC;
495 zheader.uncompressed_len = cdatalen;
496 buffer_len = ( (cdatalen * 101) / 100 ) + 100
497 + sizeof(struct CtdlCompressHeader) ;
498 destLen = (uLongf) buffer_len;
499 compressed_data = mallok(buffer_len);
501 (Bytef *) (compressed_data +
502 sizeof(struct CtdlCompressHeader)),
508 lprintf(CTDL_EMERG, "compress2() error\n");
511 zheader.compressed_len = (size_t) destLen;
512 memcpy(compressed_data, &zheader,
513 sizeof(struct CtdlCompressHeader));
514 ddata.size = (size_t) (sizeof(struct CtdlCompressHeader) +
515 zheader.compressed_len);
516 ddata.data = compressed_data;
522 ret = dbp[cdb]->put(dbp[cdb], /* db */
523 MYTID, /* transaction ID */
529 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n", cdb, db_strerror(ret));
533 if (compressing) phree(compressed_data);
540 bailIfCursor(MYCURSORS, "attempt to write during r/o cursor");
545 if ((ret = dbp[cdb]->put(dbp[cdb], /* db */
546 tid, /* transaction ID */
551 if (ret == DB_LOCK_DEADLOCK)
558 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n", cdb, db_strerror(ret));
566 if (compressing) phree(compressed_data);
575 * Delete a piece of data. Returns 0 if the operation was successful.
577 int cdb_delete(int cdb, void *key, int keylen)
584 memset(&dkey, 0, sizeof dkey);
590 ret = dbp[cdb]->del(dbp[cdb], MYTID, &dkey, 0);
593 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n", cdb, db_strerror(ret));
594 if (ret != DB_NOTFOUND)
600 bailIfCursor(MYCURSORS, "attempt to delete during r/o cursor");
605 if ((ret = dbp[cdb]->del(dbp[cdb], tid, &dkey, 0))
606 && ret != DB_NOTFOUND)
608 if (ret == DB_LOCK_DEADLOCK)
615 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n", cdb, db_strerror(ret));
627 static DBC *localcursor(int cdb)
632 if (MYCURSORS[cdb] == NULL)
633 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &curs, 0);
635 ret = MYCURSORS[cdb]->c_dup(MYCURSORS[cdb], &curs, DB_POSITION);
639 lprintf(CTDL_EMERG, "localcursor: %s\n", db_strerror(ret));
648 * Fetch a piece of data. If not found, returns NULL. Otherwise, it returns
649 * a struct cdbdata which it is the caller's responsibility to free later on
650 * using the cdb_free() routine.
652 struct cdbdata *cdb_fetch(int cdb, void *key, int keylen)
655 struct cdbdata *tempcdb;
659 memset(&dkey, 0, sizeof(DBT));
665 memset(&dret, 0, sizeof(DBT));
666 dret.flags = DB_DBT_MALLOC;
667 ret = dbp[cdb]->get(dbp[cdb], MYTID, &dkey, &dret, 0);
675 memset(&dret, 0, sizeof(DBT));
676 dret.flags = DB_DBT_MALLOC;
678 curs = localcursor(cdb);
680 ret = curs->c_get(curs, &dkey, &dret, DB_SET);
683 while (ret == DB_LOCK_DEADLOCK);
687 if ((ret != 0) && (ret != DB_NOTFOUND))
689 lprintf(CTDL_EMERG, "cdb_fetch(%d): %s\n", cdb, db_strerror(ret));
693 if (ret != 0) return NULL;
694 tempcdb = (struct cdbdata *) mallok(sizeof(struct cdbdata));
698 lprintf(CTDL_EMERG, "cdb_fetch: Cannot allocate memory for tempcdb\n");
702 tempcdb->len = dret.size;
703 tempcdb->ptr = dret.data;
705 cdb_decompress_if_necessary(tempcdb);
712 * Free a cdbdata item (ok, this is really no big deal, but we might need to do
713 * more complex stuff with other database managers in the future).
715 void cdb_free(struct cdbdata *cdb)
721 void cdb_close_cursor(int cdb)
723 if (MYCURSORS[cdb] != NULL)
724 cclose(MYCURSORS[cdb]);
726 MYCURSORS[cdb] = NULL;
730 * Prepare for a sequential search of an entire database.
731 * (There is guaranteed to be no more than one traversal in
732 * progress per thread at any given time.)
734 void cdb_rewind(int cdb)
738 if (MYCURSORS[cdb] != NULL)
739 cclose(MYCURSORS[cdb]);
742 * Now initialize the cursor
744 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &MYCURSORS[cdb], 0);
746 lprintf(CTDL_EMERG, "cdb_rewind: db_cursor: %s\n", db_strerror(ret));
753 * Fetch the next item in a sequential search. Returns a pointer to a
754 * cdbdata structure, or NULL if we've hit the end.
756 struct cdbdata *cdb_next_item(int cdb)
759 struct cdbdata *cdbret;
762 /* Initialize the key/data pair so the flags aren't set. */
763 memset(&key, 0, sizeof(key));
764 memset(&data, 0, sizeof(data));
765 data.flags = DB_DBT_MALLOC;
767 ret = MYCURSORS[cdb]->c_get(MYCURSORS[cdb],
768 &key, &data, DB_NEXT);
771 if (ret != DB_NOTFOUND) {
772 lprintf(CTDL_EMERG, "cdb_next_item(%d): %s\n",
773 cdb, db_strerror(ret));
776 cclose(MYCURSORS[cdb]);
777 MYCURSORS[cdb] = NULL;
778 return NULL; /* presumably, end of file */
781 cdbret = (struct cdbdata *) mallok(sizeof(struct cdbdata));
782 cdbret->len = data.size;
783 cdbret->ptr = data.data;
785 cdb_decompress_if_necessary(cdbret);
794 * Transaction-based stuff. I'm writing this as I bake cookies...
797 void cdb_begin_transaction(void) {
799 bailIfCursor(MYCURSORS, "can't begin transaction during r/o cursor");
803 lprintf(CTDL_EMERG, "cdb_begin_transaction: ERROR: nested transaction\n");
810 void cdb_end_transaction(void) {
813 for (i = 0; i < MAXCDB; i++)
814 if (MYCURSORS[i] != NULL) {
815 lprintf(CTDL_WARNING, "cdb_end_transaction: WARNING: cursor %d still open at transaction end\n", i);
816 cclose(MYCURSORS[i]);
822 lprintf(CTDL_EMERG, "cdb_end_transaction: ERROR: txcommit(NULL) !!\n");
832 * Truncate (delete every record)
834 void cdb_trunc(int cdb)
842 lprintf(CTDL_EMERG, "cdb_trunc must not be called in a transaction.\n");
847 bailIfCursor(MYCURSORS, "attempt to write during r/o cursor");
852 if ((ret = dbp[cdb]->truncate(dbp[cdb], /* db */
853 tid, /* transaction ID */
854 &count, /* #rows deleted */
857 if (ret == DB_LOCK_DEADLOCK)
864 lprintf(CTDL_EMERG, "cdb_truncate(%d): %s\n", cdb, db_strerror(ret));