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)
40 #elif defined(HAVE_DB3_DB_H)
43 #error Neither <db.h> nor <db3/db.h> was found by configure. Install db3-devel.
49 #include "dynloader.h"
50 #include "citserver.h"
53 #include "sysdep_decls.h"
55 static DB *dbp[MAXCDB]; /* One DB handle for each Citadel database */
56 static DB_ENV *dbenv; /* The DB environment (global) */
58 struct cdbtsd { /* Thread-specific DB stuff */
59 DB_TXN *tid; /* Transaction handle */
60 DBC *cursors[MAXCDB]; /* Cursors, for traversals... */
67 static pthread_key_t tsdkey;
69 #define MYCURSORS (((struct cdbtsd*)pthread_getspecific(tsdkey))->cursors)
70 #define MYTID (((struct cdbtsd*)pthread_getspecific(tsdkey))->tid)
72 /* just a little helper function */
73 static void txabort(DB_TXN *tid) {
74 int ret = txn_abort(tid);
77 lprintf(1, "cdb_*: txn_abort: %s\n", db_strerror(ret));
82 /* this one is even more helpful than the last. */
83 static void txcommit(DB_TXN *tid) {
84 int ret = txn_commit(tid, 0);
87 lprintf(1, "cdb_*: txn_commit: %s\n", db_strerror(ret));
92 /* are you sensing a pattern yet? */
93 static void txbegin(DB_TXN **tid) {
94 int ret = txn_begin(dbenv, NULL, tid, 0);
97 lprintf(1, "cdb_*: txn_begin: %s\n", db_strerror(ret));
102 static void cclose(DBC *cursor) {
105 if ((ret = cursor->c_close(cursor))) {
106 lprintf(1, "cdb_*: c_close: %s\n", db_strerror(ret));
111 static void bailIfCursor(DBC **cursors, const char *msg)
115 for (i = 0; i < MAXCDB; i++)
116 if (cursors[i] != NULL)
118 lprintf(1, "cdb_*: cursor still in progress on cdb %d: %s\n", i, msg);
123 static void check_handles(void *arg) {
125 struct cdbtsd *tsd = (struct cdbtsd *)arg;
127 bailIfCursor(tsd->cursors, "in check_handles");
129 if (tsd->tid != NULL) {
130 lprintf(1, "cdb_*: transaction still in progress!");
136 static void dest_tsd(void *arg) {
144 * Ensure that we have a key for thread-specific data. We don't
145 * put anything in here that Citadel cares about; this is just database
146 * related stuff like cursors and transactions.
148 * This should be called immediately after startup by any thread which wants
149 * to use database calls, except for whatever thread calls open_databases.
151 void cdb_allocate_tsd(void) {
154 if (pthread_getspecific(tsdkey) != NULL)
157 tsd = mallok(sizeof *tsd);
161 memset(tsd->cursors, 0, sizeof tsd->cursors);
162 pthread_setspecific(tsdkey, tsd);
165 void cdb_free_tsd(void) {
166 dest_tsd(pthread_getspecific(tsdkey));
167 pthread_setspecific(tsdkey, NULL);
170 void cdb_check_handles(void) {
171 check_handles(pthread_getspecific(tsdkey));
176 * Reclaim unused space in the databases. We need to do each one of
177 * these discretely, rather than in a loop.
179 * This is a stub function in the Sleepycat DB backend, because there is no
180 * such API call available.
182 void defrag_databases(void)
189 * Cull the database logs
191 static void cdb_cull_logs(void) {
197 lprintf(5, "Database log file cull started.\n");
201 /* Get the list of names. */
202 #if DB_VERSION_MAJOR == 3 && DB_VERSION_MINOR < 3
203 if ((ret = log_archive(dbenv, &list, flags, NULL)) != 0) {
204 #elif DB_VERSION_MAJOR >= 4
205 if ((ret = dbenv->log_archive(dbenv, &list, flags)) != 0) {
207 if ((ret = log_archive(dbenv, &list, flags)) != 0) {
209 lprintf(1, "cdb_cull_logs: %s\n", db_strerror(ret));
213 /* Print the list of names. */
215 for (file = list; *file != NULL; ++file) {
216 lprintf(9, "Deleting log: %s\n", *file);
219 snprintf(errmsg, sizeof(errmsg),
220 " ** ERROR **\n \n \n "
221 "Citadel was unable to delete the "
222 "database log file '%s' because of the "
223 "following error:\n \n %s\n \n"
224 " This log file is no longer in use "
225 "and may be safely deleted.\n",
228 aide_message(errmsg);
234 lprintf(5, "Database log file cull ended.\n");
239 * Request a checkpoint of the database.
241 static void cdb_checkpoint(void) {
243 static time_t last_cull = 0L;
245 #if DB_VERSION_MAJOR >= 4
246 ret = dbenv->txn_checkpoint(dbenv,
248 ret = txn_checkpoint(dbenv,
250 MAX_CHECKPOINT_KBYTES,
251 MAX_CHECKPOINT_MINUTES,
253 if ( (ret != 0) && (ret != DB_INCOMPLETE) ) {
254 lprintf(1, "cdb_checkpoint: txn_checkpoint: %s\n", db_strerror(ret));
258 if (ret == DB_INCOMPLETE) {
259 lprintf(3, "WARNING: txn_checkpoint: %s\n", db_strerror(ret));
262 /* Cull the logs if we haven't done so for 24 hours */
263 if ((time(NULL) - last_cull) > 86400L) {
264 last_cull = time(NULL);
271 * Open the various databases we'll be using. Any database which
272 * does not exist should be created. Note that we don't need an S_DATABASE
273 * critical section here, because there aren't any active threads manipulating
274 * the database yet -- and besides, it causes problems on BSDI.
276 void open_databases(void)
280 char dbfilename[SIZ];
283 lprintf(9, "cdb_*: open_databases() starting\n");
285 lprintf(5, "zlib compression version %s\n", zlibVersion());
289 * Silently try to create the database subdirectory. If it's
290 * already there, no problem.
292 system("exec mkdir data 2>/dev/null");
294 lprintf(9, "cdb_*: Setting up DB environment\n");
295 db_env_set_func_yield(sched_yield);
296 ret = db_env_create(&dbenv, 0);
298 lprintf(1, "cdb_*: db_env_create: %s\n", db_strerror(ret));
301 dbenv->set_errpfx(dbenv, "citserver");
304 * We want to specify the shared memory buffer pool cachesize,
305 * but everything else is the default.
307 ret = dbenv->set_cachesize(dbenv, 0, 64 * 1024, 0);
309 lprintf(1, "cdb_*: set_cachesize: %s\n", db_strerror(ret));
310 dbenv->close(dbenv, 0);
314 if ((ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT))) {
315 lprintf(1, "cdb_*: set_lk_detect: %s\n", db_strerror(ret));
316 dbenv->close(dbenv, 0);
320 flags = DB_CREATE|DB_RECOVER|DB_INIT_MPOOL|DB_PRIVATE|DB_INIT_TXN|
321 DB_INIT_LOCK|DB_THREAD;
322 ret = dbenv->open(dbenv, "./data", flags, 0);
324 lprintf(1, "cdb_*: dbenv->open: %s\n", db_strerror(ret));
325 dbenv->close(dbenv, 0);
329 lprintf(7, "cdb_*: Starting up DB\n");
331 for (i = 0; i < MAXCDB; ++i) {
333 /* Create a database handle */
334 ret = db_create(&dbp[i], dbenv, 0);
336 lprintf(1, "cdb_*: db_create: %s\n", db_strerror(ret));
341 /* Arbitrary names for our tables -- we reference them by
342 * number, so we don't have string names for them.
344 snprintf(dbfilename, sizeof dbfilename, "cdb.%02x", i);
346 ret = dbp[i]->open(dbp[i],
353 lprintf(1, "cdb_*: db_open[%d]: %s\n", i, db_strerror(ret));
358 if ((ret = pthread_key_create(&tsdkey, dest_tsd))) {
359 lprintf(1, "cdb_*: pthread_key_create: %s\n", strerror(ret));
364 CtdlRegisterSessionHook(cdb_checkpoint, EVT_TIMER);
365 lprintf(9, "cdb_*: open_databases() finished\n");
370 * Close all of the db database files we've opened. This can be done
371 * in a loop, since it's just a bunch of closes.
373 void close_databases(void)
380 #if DB_VERSION_MAJOR >= 4
381 if ((ret = dbenv->txn_checkpoint(dbenv, 0, 0, 0))) {
383 if ((ret = txn_checkpoint(dbenv, 0, 0, 0))) {
385 lprintf(1, "cdb_*: txn_checkpoint: %s\n", db_strerror(ret));
389 for (a = 0; a < MAXCDB; ++a) {
390 lprintf(7, "cdb_*: Closing database %d\n", a);
391 ret = dbp[a]->close(dbp[a], 0);
393 lprintf(1, "cdb_*: db_close: %s\n", db_strerror(ret));
399 /* Close the handle. */
400 ret = dbenv->close(dbenv, 0);
402 lprintf(1, "cdb_*: DBENV->close: %s\n", db_strerror(ret));
409 * Compression functions only used if we have zlib
413 void cdb_decompress_if_necessary(struct cdbdata *cdb) {
414 static int magic = COMPRESS_MAGIC;
415 struct CtdlCompressHeader zheader;
416 char *uncompressed_data;
417 char *compressed_data;
418 uLongf destLen, sourceLen;
420 if (cdb == NULL) return;
421 if (cdb->ptr == NULL) return;
422 if (memcmp(cdb->ptr, &magic, sizeof(magic))) return;
424 /* At this point we know we're looking at a compressed item. */
425 memcpy(&zheader, cdb->ptr, sizeof(struct CtdlCompressHeader));
427 compressed_data = cdb->ptr;
428 compressed_data += sizeof(struct CtdlCompressHeader);
430 sourceLen = (uLongf) zheader.compressed_len;
431 destLen = (uLongf) zheader.uncompressed_len;
432 uncompressed_data = mallok(zheader.uncompressed_len);
434 if (uncompress( (Bytef *) uncompressed_data,
439 lprintf(1, "uncompress() error\n");
444 cdb->len = (size_t) destLen;
445 cdb->ptr = uncompressed_data;
448 #endif /* HAVE_ZLIB */
452 * Store a piece of data. Returns 0 if the operation was successful. If a
453 * key already exists it should be overwritten.
455 int cdb_store(int cdb,
456 void *ckey, int ckeylen,
457 void *cdata, int cdatalen)
465 struct CtdlCompressHeader zheader;
466 char *compressed_data = NULL;
472 memset(&dkey, 0, sizeof(DBT));
473 memset(&ddata, 0, sizeof(DBT));
476 ddata.size = cdatalen;
480 /* Only compress Visit records. Everything else is uncompressed. */
481 if (cdb == CDB_VISIT) {
483 zheader.magic = COMPRESS_MAGIC;
484 zheader.uncompressed_len = cdatalen;
485 buffer_len = ( (cdatalen * 101) / 100 ) + 100
486 + sizeof(struct CtdlCompressHeader) ;
487 destLen = (uLongf) buffer_len;
488 compressed_data = mallok(buffer_len);
490 (Bytef *) (compressed_data +
491 sizeof(struct CtdlCompressHeader)),
497 lprintf(1, "compress2() error\n");
500 zheader.compressed_len = (size_t) destLen;
501 memcpy(compressed_data, &zheader,
502 sizeof(struct CtdlCompressHeader));
503 ddata.size = (size_t) (sizeof(struct CtdlCompressHeader) +
504 zheader.compressed_len);
505 ddata.data = compressed_data;
511 ret = dbp[cdb]->put(dbp[cdb], /* db */
512 MYTID, /* transaction ID */
518 lprintf(1, "cdb_store(%d): %s\n", cdb,
523 if (compressing) phree(compressed_data);
530 bailIfCursor(MYCURSORS, "attempt to write during r/o cursor");
535 if ((ret = dbp[cdb]->put(dbp[cdb], /* db */
536 tid, /* transaction ID */
541 if (ret == DB_LOCK_DEADLOCK)
548 lprintf(1, "cdb_store(%d): %s\n", cdb,
557 if (compressing) phree(compressed_data);
566 * Delete a piece of data. Returns 0 if the operation was successful.
568 int cdb_delete(int cdb, void *key, int keylen)
575 memset(&dkey, 0, sizeof dkey);
581 ret = dbp[cdb]->del(dbp[cdb], MYTID, &dkey, 0);
584 lprintf(1, "cdb_delete(%d): %s\n", cdb,
586 if (ret != DB_NOTFOUND)
592 bailIfCursor(MYCURSORS, "attempt to delete during r/o cursor");
597 if ((ret = dbp[cdb]->del(dbp[cdb], tid, &dkey, 0))
598 && ret != DB_NOTFOUND)
600 if (ret == DB_LOCK_DEADLOCK)
607 lprintf(1, "cdb_delete(%d): %s\n", cdb,
620 static DBC *localcursor(int cdb)
625 if (MYCURSORS[cdb] == NULL)
626 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &curs, 0);
628 ret = MYCURSORS[cdb]->c_dup(MYCURSORS[cdb], &curs, DB_POSITION);
632 lprintf(1, "localcursor: %s\n", db_strerror(ret));
641 * Fetch a piece of data. If not found, returns NULL. Otherwise, it returns
642 * a struct cdbdata which it is the caller's responsibility to free later on
643 * using the cdb_free() routine.
645 struct cdbdata *cdb_fetch(int cdb, void *key, int keylen)
648 struct cdbdata *tempcdb;
652 memset(&dkey, 0, sizeof(DBT));
658 memset(&dret, 0, sizeof(DBT));
659 dret.flags = DB_DBT_MALLOC;
660 ret = dbp[cdb]->get(dbp[cdb], MYTID, &dkey, &dret, 0);
668 memset(&dret, 0, sizeof(DBT));
669 dret.flags = DB_DBT_MALLOC;
671 curs = localcursor(cdb);
673 ret = curs->c_get(curs, &dkey, &dret, DB_SET);
676 while (ret == DB_LOCK_DEADLOCK);
680 if ((ret != 0) && (ret != DB_NOTFOUND))
682 lprintf(1, "cdb_fetch(%d): %s\n", cdb, db_strerror(ret));
686 if (ret != 0) return NULL;
687 tempcdb = (struct cdbdata *) mallok(sizeof(struct cdbdata));
691 lprintf(2, "cdb_fetch: Cannot allocate memory for tempcdb\n");
695 tempcdb->len = dret.size;
696 tempcdb->ptr = dret.data;
697 cdb_decompress_if_necessary(tempcdb);
703 * Free a cdbdata item (ok, this is really no big deal, but we might need to do
704 * more complex stuff with other database managers in the future).
706 void cdb_free(struct cdbdata *cdb)
712 void cdb_close_cursor(int cdb)
714 if (MYCURSORS[cdb] != NULL)
715 cclose(MYCURSORS[cdb]);
717 MYCURSORS[cdb] = NULL;
721 * Prepare for a sequential search of an entire database.
722 * (There is guaranteed to be no more than one traversal in
723 * progress per thread at any given time.)
725 void cdb_rewind(int cdb)
729 if (MYCURSORS[cdb] != NULL)
730 cclose(MYCURSORS[cdb]);
733 * Now initialize the cursor
735 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &MYCURSORS[cdb], 0);
737 lprintf(1, "cdb_rewind: db_cursor: %s\n", db_strerror(ret));
744 * Fetch the next item in a sequential search. Returns a pointer to a
745 * cdbdata structure, or NULL if we've hit the end.
747 struct cdbdata *cdb_next_item(int cdb)
750 struct cdbdata *cdbret;
753 /* Initialize the key/data pair so the flags aren't set. */
754 memset(&key, 0, sizeof(key));
755 memset(&data, 0, sizeof(data));
756 data.flags = DB_DBT_MALLOC;
758 ret = MYCURSORS[cdb]->c_get(MYCURSORS[cdb],
759 &key, &data, DB_NEXT);
762 if (ret != DB_NOTFOUND) {
763 lprintf(1, "cdb_next_item(%d): %s\n",
764 cdb, db_strerror(ret));
767 cclose(MYCURSORS[cdb]);
768 MYCURSORS[cdb] = NULL;
769 return NULL; /* presumably, end of file */
772 cdbret = (struct cdbdata *) mallok(sizeof(struct cdbdata));
773 cdbret->len = data.size;
774 cdbret->ptr = data.data;
775 cdb_decompress_if_necessary(cdbret);
783 * Transaction-based stuff. I'm writing this as I bake cookies...
786 void cdb_begin_transaction(void) {
788 bailIfCursor(MYCURSORS, "can't begin transaction during r/o cursor");
792 lprintf(1, "cdb_begin_transaction: ERROR: nested transaction\n");
799 void cdb_end_transaction(void) {
802 for (i = 0; i < MAXCDB; i++)
803 if (MYCURSORS[i] != NULL) {
804 lprintf(1, "cdb_end_transaction: WARNING: cursor %d still open at transaction end\n", i);
805 cclose(MYCURSORS[i]);
811 lprintf(1, "cdb_end_transaction: ERROR: txcommit(NULL) !!\n");
821 * Truncate (delete every record)
823 void cdb_trunc(int cdb)
827 #if DB_VERSION_MAJOR > 3 || DB_VERSION_MINOR > 2
833 lprintf(1, "cdb_trunc must not be called in a transaction.\n");
838 bailIfCursor(MYCURSORS, "attempt to write during r/o cursor");
840 #if DB_VERSION_MAJOR == 3 && DB_VERSION_MINOR < 3
845 /* Initialize the key/data pair so the flags aren't set. */
846 memset(&key, 0, sizeof(key));
847 memset(&data, 0, sizeof(data));
851 ret = dbp[cdb]->cursor(dbp[cdb], tid, &MYCURSORS[cdb], 0);
854 lprintf(1, "cdb_trunc: db_cursor: %s\n", db_strerror(ret));
858 ret = MYCURSORS[cdb]->c_get(MYCURSORS[cdb],
859 &key, &data, DB_NEXT);
862 cclose(MYCURSORS[cdb]);
864 if (ret == DB_LOCK_DEADLOCK)
867 if (ret == DB_NOTFOUND)
870 lprintf(1, "cdb_trunc: c_get: %s\n", db_strerror(ret));
874 ret = MYCURSORS[cdb]->c_del(MYCURSORS[cdb], 0);
877 cclose(MYCURSORS[cdb]);
879 if (ret == DB_LOCK_DEADLOCK)
882 lprintf(1, "cdb_trunc: c_del: %s\n", db_strerror(ret));
886 cclose(MYCURSORS[cdb]);
893 if ((ret = dbp[cdb]->truncate(dbp[cdb], /* db */
894 tid, /* transaction ID */
895 &count, /* #rows deleted */
898 if (ret == DB_LOCK_DEADLOCK)
905 lprintf(1, "cdb_truncate(%d): %s\n", cdb,