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(struct cdbtsd));
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,
254 /* The DB_INCOMPLETE error is no longer possible (or even defined) as of
255 * Berkeley DB v4.1. When we get to the point where v4.0 and earlier are no
256 * longer supported, we can remove this ifdef.
259 if ( (ret != 0) && (ret != DB_INCOMPLETE) ) {
260 lprintf(1, "cdb_checkpoint: txn_checkpoint: %s\n",
264 if (ret == DB_INCOMPLETE) {
265 lprintf(3, "WARNING: txn_checkpoint: %s\n", db_strerror(ret));
267 #else /* DB_INCOMPLETE */
269 lprintf(1, "cdb_checkpoint: txn_checkpoint: %s\n",
273 #endif /* DB_INCOMPLETE */
275 /* Cull the logs if we haven't done so for 24 hours */
276 if ((time(NULL) - last_cull) > 86400L) {
277 last_cull = time(NULL);
284 * Open the various databases we'll be using. Any database which
285 * does not exist should be created. Note that we don't need an S_DATABASE
286 * critical section here, because there aren't any active threads manipulating
287 * the database yet -- and besides, it causes problems on BSDI.
289 void open_databases(void)
293 char dbfilename[SIZ];
296 lprintf(9, "cdb_*: open_databases() starting\n");
298 lprintf(5, "zlib compression version %s\n", zlibVersion());
302 * Silently try to create the database subdirectory. If it's
303 * already there, no problem.
305 system("exec mkdir data 2>/dev/null");
307 lprintf(9, "cdb_*: Setting up DB environment\n");
308 db_env_set_func_yield(sched_yield);
309 ret = db_env_create(&dbenv, 0);
311 lprintf(1, "cdb_*: db_env_create: %s\n", db_strerror(ret));
314 dbenv->set_errpfx(dbenv, "citserver");
317 * We want to specify the shared memory buffer pool cachesize,
318 * but everything else is the default.
320 ret = dbenv->set_cachesize(dbenv, 0, 64 * 1024, 0);
322 lprintf(1, "cdb_*: set_cachesize: %s\n", db_strerror(ret));
323 dbenv->close(dbenv, 0);
327 if ((ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT))) {
328 lprintf(1, "cdb_*: set_lk_detect: %s\n", db_strerror(ret));
329 dbenv->close(dbenv, 0);
333 flags = DB_CREATE|DB_RECOVER|DB_INIT_MPOOL|DB_PRIVATE|DB_INIT_TXN|
334 DB_INIT_LOCK|DB_THREAD;
335 ret = dbenv->open(dbenv, "./data", flags, 0);
337 lprintf(1, "cdb_*: dbenv->open: %s\n", db_strerror(ret));
338 dbenv->close(dbenv, 0);
342 lprintf(7, "cdb_*: Starting up DB\n");
344 for (i = 0; i < MAXCDB; ++i) {
346 /* Create a database handle */
347 ret = db_create(&dbp[i], dbenv, 0);
349 lprintf(1, "cdb_*: db_create: %s\n", db_strerror(ret));
354 /* Arbitrary names for our tables -- we reference them by
355 * number, so we don't have string names for them.
357 snprintf(dbfilename, sizeof dbfilename, "cdb.%02x", i);
359 ret = dbp[i]->open(dbp[i],
360 #if DB_VERSION_MAJOR >= 4 && DB_VERSION_MINOR >= 1
361 NULL, /* new parameter */
369 lprintf(1, "cdb_*: db_open[%d]: %s\n", i, db_strerror(ret));
374 if ((ret = pthread_key_create(&tsdkey, dest_tsd))) {
375 lprintf(1, "cdb_*: pthread_key_create: %s\n", strerror(ret));
380 CtdlRegisterSessionHook(cdb_checkpoint, EVT_TIMER);
381 lprintf(9, "cdb_*: open_databases() finished\n");
386 * Close all of the db database files we've opened. This can be done
387 * in a loop, since it's just a bunch of closes.
389 void close_databases(void)
396 #if DB_VERSION_MAJOR >= 4
397 if ((ret = dbenv->txn_checkpoint(dbenv, 0, 0, 0))) {
399 if ((ret = txn_checkpoint(dbenv, 0, 0, 0))) {
401 lprintf(1, "cdb_*: txn_checkpoint: %s\n", db_strerror(ret));
405 for (a = 0; a < MAXCDB; ++a) {
406 lprintf(7, "cdb_*: Closing database %d\n", a);
407 ret = dbp[a]->close(dbp[a], 0);
409 lprintf(1, "cdb_*: db_close: %s\n", db_strerror(ret));
415 /* Close the handle. */
416 ret = dbenv->close(dbenv, 0);
418 lprintf(1, "cdb_*: DBENV->close: %s\n", db_strerror(ret));
425 * Compression functions only used if we have zlib
429 void cdb_decompress_if_necessary(struct cdbdata *cdb) {
430 static int magic = COMPRESS_MAGIC;
431 struct CtdlCompressHeader zheader;
432 char *uncompressed_data;
433 char *compressed_data;
434 uLongf destLen, sourceLen;
436 if (cdb == NULL) return;
437 if (cdb->ptr == NULL) return;
438 if (memcmp(cdb->ptr, &magic, sizeof(magic))) return;
440 /* At this point we know we're looking at a compressed item. */
441 memcpy(&zheader, cdb->ptr, sizeof(struct CtdlCompressHeader));
443 compressed_data = cdb->ptr;
444 compressed_data += sizeof(struct CtdlCompressHeader);
446 sourceLen = (uLongf) zheader.compressed_len;
447 destLen = (uLongf) zheader.uncompressed_len;
448 uncompressed_data = mallok(zheader.uncompressed_len);
450 if (uncompress( (Bytef *) uncompressed_data,
455 lprintf(1, "uncompress() error\n");
460 cdb->len = (size_t) destLen;
461 cdb->ptr = uncompressed_data;
464 #endif /* HAVE_ZLIB */
468 * Store a piece of data. Returns 0 if the operation was successful. If a
469 * key already exists it should be overwritten.
471 int cdb_store(int cdb,
472 void *ckey, int ckeylen,
473 void *cdata, int cdatalen)
481 struct CtdlCompressHeader zheader;
482 char *compressed_data = NULL;
488 memset(&dkey, 0, sizeof(DBT));
489 memset(&ddata, 0, sizeof(DBT));
492 ddata.size = cdatalen;
496 /* Only compress Visit records. Everything else is uncompressed. */
497 if (cdb == CDB_VISIT) {
499 zheader.magic = COMPRESS_MAGIC;
500 zheader.uncompressed_len = cdatalen;
501 buffer_len = ( (cdatalen * 101) / 100 ) + 100
502 + sizeof(struct CtdlCompressHeader) ;
503 destLen = (uLongf) buffer_len;
504 compressed_data = mallok(buffer_len);
506 (Bytef *) (compressed_data +
507 sizeof(struct CtdlCompressHeader)),
513 lprintf(1, "compress2() error\n");
516 zheader.compressed_len = (size_t) destLen;
517 memcpy(compressed_data, &zheader,
518 sizeof(struct CtdlCompressHeader));
519 ddata.size = (size_t) (sizeof(struct CtdlCompressHeader) +
520 zheader.compressed_len);
521 ddata.data = compressed_data;
527 ret = dbp[cdb]->put(dbp[cdb], /* db */
528 MYTID, /* transaction ID */
534 lprintf(1, "cdb_store(%d): %s\n", cdb,
539 if (compressing) phree(compressed_data);
546 bailIfCursor(MYCURSORS, "attempt to write during r/o cursor");
551 if ((ret = dbp[cdb]->put(dbp[cdb], /* db */
552 tid, /* transaction ID */
557 if (ret == DB_LOCK_DEADLOCK)
564 lprintf(1, "cdb_store(%d): %s\n", cdb,
573 if (compressing) phree(compressed_data);
582 * Delete a piece of data. Returns 0 if the operation was successful.
584 int cdb_delete(int cdb, void *key, int keylen)
591 memset(&dkey, 0, sizeof dkey);
597 ret = dbp[cdb]->del(dbp[cdb], MYTID, &dkey, 0);
600 lprintf(1, "cdb_delete(%d): %s\n", cdb,
602 if (ret != DB_NOTFOUND)
608 bailIfCursor(MYCURSORS, "attempt to delete during r/o cursor");
613 if ((ret = dbp[cdb]->del(dbp[cdb], tid, &dkey, 0))
614 && ret != DB_NOTFOUND)
616 if (ret == DB_LOCK_DEADLOCK)
623 lprintf(1, "cdb_delete(%d): %s\n", cdb,
636 static DBC *localcursor(int cdb)
641 if (MYCURSORS[cdb] == NULL)
642 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &curs, 0);
644 ret = MYCURSORS[cdb]->c_dup(MYCURSORS[cdb], &curs, DB_POSITION);
648 lprintf(1, "localcursor: %s\n", db_strerror(ret));
657 * Fetch a piece of data. If not found, returns NULL. Otherwise, it returns
658 * a struct cdbdata which it is the caller's responsibility to free later on
659 * using the cdb_free() routine.
661 struct cdbdata *cdb_fetch(int cdb, void *key, int keylen)
664 struct cdbdata *tempcdb;
668 memset(&dkey, 0, sizeof(DBT));
674 memset(&dret, 0, sizeof(DBT));
675 dret.flags = DB_DBT_MALLOC;
676 ret = dbp[cdb]->get(dbp[cdb], MYTID, &dkey, &dret, 0);
684 memset(&dret, 0, sizeof(DBT));
685 dret.flags = DB_DBT_MALLOC;
687 curs = localcursor(cdb);
689 ret = curs->c_get(curs, &dkey, &dret, DB_SET);
692 while (ret == DB_LOCK_DEADLOCK);
696 if ((ret != 0) && (ret != DB_NOTFOUND))
698 lprintf(1, "cdb_fetch(%d): %s\n", cdb, db_strerror(ret));
702 if (ret != 0) return NULL;
703 tempcdb = (struct cdbdata *) mallok(sizeof(struct cdbdata));
707 lprintf(2, "cdb_fetch: Cannot allocate memory for tempcdb\n");
711 tempcdb->len = dret.size;
712 tempcdb->ptr = dret.data;
714 cdb_decompress_if_necessary(tempcdb);
721 * Free a cdbdata item (ok, this is really no big deal, but we might need to do
722 * more complex stuff with other database managers in the future).
724 void cdb_free(struct cdbdata *cdb)
730 void cdb_close_cursor(int cdb)
732 if (MYCURSORS[cdb] != NULL)
733 cclose(MYCURSORS[cdb]);
735 MYCURSORS[cdb] = NULL;
739 * Prepare for a sequential search of an entire database.
740 * (There is guaranteed to be no more than one traversal in
741 * progress per thread at any given time.)
743 void cdb_rewind(int cdb)
747 if (MYCURSORS[cdb] != NULL)
748 cclose(MYCURSORS[cdb]);
751 * Now initialize the cursor
753 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &MYCURSORS[cdb], 0);
755 lprintf(1, "cdb_rewind: db_cursor: %s\n", db_strerror(ret));
762 * Fetch the next item in a sequential search. Returns a pointer to a
763 * cdbdata structure, or NULL if we've hit the end.
765 struct cdbdata *cdb_next_item(int cdb)
768 struct cdbdata *cdbret;
771 /* Initialize the key/data pair so the flags aren't set. */
772 memset(&key, 0, sizeof(key));
773 memset(&data, 0, sizeof(data));
774 data.flags = DB_DBT_MALLOC;
776 ret = MYCURSORS[cdb]->c_get(MYCURSORS[cdb],
777 &key, &data, DB_NEXT);
780 if (ret != DB_NOTFOUND) {
781 lprintf(1, "cdb_next_item(%d): %s\n",
782 cdb, db_strerror(ret));
785 cclose(MYCURSORS[cdb]);
786 MYCURSORS[cdb] = NULL;
787 return NULL; /* presumably, end of file */
790 cdbret = (struct cdbdata *) mallok(sizeof(struct cdbdata));
791 cdbret->len = data.size;
792 cdbret->ptr = data.data;
794 cdb_decompress_if_necessary(cdbret);
803 * Transaction-based stuff. I'm writing this as I bake cookies...
806 void cdb_begin_transaction(void) {
808 bailIfCursor(MYCURSORS, "can't begin transaction during r/o cursor");
812 lprintf(1, "cdb_begin_transaction: ERROR: nested transaction\n");
819 void cdb_end_transaction(void) {
822 for (i = 0; i < MAXCDB; i++)
823 if (MYCURSORS[i] != NULL) {
824 lprintf(1, "cdb_end_transaction: WARNING: cursor %d still open at transaction end\n", i);
825 cclose(MYCURSORS[i]);
831 lprintf(1, "cdb_end_transaction: ERROR: txcommit(NULL) !!\n");
841 * Truncate (delete every record)
843 void cdb_trunc(int cdb)
847 #if DB_VERSION_MAJOR > 3 || DB_VERSION_MINOR > 2
853 lprintf(1, "cdb_trunc must not be called in a transaction.\n");
858 bailIfCursor(MYCURSORS, "attempt to write during r/o cursor");
860 #if DB_VERSION_MAJOR == 3 && DB_VERSION_MINOR < 3
865 /* Initialize the key/data pair so the flags aren't set. */
866 memset(&key, 0, sizeof(key));
867 memset(&data, 0, sizeof(data));
871 ret = dbp[cdb]->cursor(dbp[cdb], tid, &MYCURSORS[cdb], 0);
874 lprintf(1, "cdb_trunc: db_cursor: %s\n", db_strerror(ret));
878 ret = MYCURSORS[cdb]->c_get(MYCURSORS[cdb],
879 &key, &data, DB_NEXT);
882 cclose(MYCURSORS[cdb]);
884 if (ret == DB_LOCK_DEADLOCK)
887 if (ret == DB_NOTFOUND)
890 lprintf(1, "cdb_trunc: c_get: %s\n", db_strerror(ret));
894 ret = MYCURSORS[cdb]->c_del(MYCURSORS[cdb], 0);
897 cclose(MYCURSORS[cdb]);
899 if (ret == DB_LOCK_DEADLOCK)
902 lprintf(1, "cdb_trunc: c_del: %s\n", db_strerror(ret));
906 cclose(MYCURSORS[cdb]);
913 if ((ret = dbp[cdb]->truncate(dbp[cdb], /* db */
914 tid, /* transaction ID */
915 &count, /* #rows deleted */
918 if (ret == DB_LOCK_DEADLOCK)
925 lprintf(1, "cdb_truncate(%d): %s\n", cdb,