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 */
367 #if DB_VERSION_MAJOR >= 4 && DB_VERSION_MINOR >= 1
373 lprintf(1, "cdb_*: db_open[%d]: %s\n", i, db_strerror(ret));
378 if ((ret = pthread_key_create(&tsdkey, dest_tsd))) {
379 lprintf(1, "cdb_*: pthread_key_create: %s\n", strerror(ret));
384 CtdlRegisterSessionHook(cdb_checkpoint, EVT_TIMER);
385 lprintf(9, "cdb_*: open_databases() finished\n");
390 * Close all of the db database files we've opened. This can be done
391 * in a loop, since it's just a bunch of closes.
393 void close_databases(void)
400 #if DB_VERSION_MAJOR >= 4
401 if ((ret = dbenv->txn_checkpoint(dbenv, 0, 0, 0))) {
403 if ((ret = txn_checkpoint(dbenv, 0, 0, 0))) {
405 lprintf(1, "cdb_*: txn_checkpoint: %s\n", db_strerror(ret));
409 for (a = 0; a < MAXCDB; ++a) {
410 lprintf(7, "cdb_*: Closing database %d\n", a);
411 ret = dbp[a]->close(dbp[a], 0);
413 lprintf(1, "cdb_*: db_close: %s\n", db_strerror(ret));
419 /* Close the handle. */
420 ret = dbenv->close(dbenv, 0);
422 lprintf(1, "cdb_*: DBENV->close: %s\n", db_strerror(ret));
429 * Compression functions only used if we have zlib
433 void cdb_decompress_if_necessary(struct cdbdata *cdb) {
434 static int magic = COMPRESS_MAGIC;
435 struct CtdlCompressHeader zheader;
436 char *uncompressed_data;
437 char *compressed_data;
438 uLongf destLen, sourceLen;
440 if (cdb == NULL) return;
441 if (cdb->ptr == NULL) return;
442 if (memcmp(cdb->ptr, &magic, sizeof(magic))) return;
444 /* At this point we know we're looking at a compressed item. */
445 memcpy(&zheader, cdb->ptr, sizeof(struct CtdlCompressHeader));
447 compressed_data = cdb->ptr;
448 compressed_data += sizeof(struct CtdlCompressHeader);
450 sourceLen = (uLongf) zheader.compressed_len;
451 destLen = (uLongf) zheader.uncompressed_len;
452 uncompressed_data = mallok(zheader.uncompressed_len);
454 if (uncompress( (Bytef *) uncompressed_data,
459 lprintf(1, "uncompress() error\n");
464 cdb->len = (size_t) destLen;
465 cdb->ptr = uncompressed_data;
468 #endif /* HAVE_ZLIB */
472 * Store a piece of data. Returns 0 if the operation was successful. If a
473 * key already exists it should be overwritten.
475 int cdb_store(int cdb,
476 void *ckey, int ckeylen,
477 void *cdata, int cdatalen)
485 struct CtdlCompressHeader zheader;
486 char *compressed_data = NULL;
492 memset(&dkey, 0, sizeof(DBT));
493 memset(&ddata, 0, sizeof(DBT));
496 ddata.size = cdatalen;
500 /* Only compress Visit records. Everything else is uncompressed. */
501 if (cdb == CDB_VISIT) {
503 zheader.magic = COMPRESS_MAGIC;
504 zheader.uncompressed_len = cdatalen;
505 buffer_len = ( (cdatalen * 101) / 100 ) + 100
506 + sizeof(struct CtdlCompressHeader) ;
507 destLen = (uLongf) buffer_len;
508 compressed_data = mallok(buffer_len);
510 (Bytef *) (compressed_data +
511 sizeof(struct CtdlCompressHeader)),
517 lprintf(1, "compress2() error\n");
520 zheader.compressed_len = (size_t) destLen;
521 memcpy(compressed_data, &zheader,
522 sizeof(struct CtdlCompressHeader));
523 ddata.size = (size_t) (sizeof(struct CtdlCompressHeader) +
524 zheader.compressed_len);
525 ddata.data = compressed_data;
531 ret = dbp[cdb]->put(dbp[cdb], /* db */
532 MYTID, /* transaction ID */
538 lprintf(1, "cdb_store(%d): %s\n", cdb,
543 if (compressing) phree(compressed_data);
550 bailIfCursor(MYCURSORS, "attempt to write during r/o cursor");
555 if ((ret = dbp[cdb]->put(dbp[cdb], /* db */
556 tid, /* transaction ID */
561 if (ret == DB_LOCK_DEADLOCK)
568 lprintf(1, "cdb_store(%d): %s\n", cdb,
577 if (compressing) phree(compressed_data);
586 * Delete a piece of data. Returns 0 if the operation was successful.
588 int cdb_delete(int cdb, void *key, int keylen)
595 memset(&dkey, 0, sizeof dkey);
601 ret = dbp[cdb]->del(dbp[cdb], MYTID, &dkey, 0);
604 lprintf(1, "cdb_delete(%d): %s\n", cdb,
606 if (ret != DB_NOTFOUND)
612 bailIfCursor(MYCURSORS, "attempt to delete during r/o cursor");
617 if ((ret = dbp[cdb]->del(dbp[cdb], tid, &dkey, 0))
618 && ret != DB_NOTFOUND)
620 if (ret == DB_LOCK_DEADLOCK)
627 lprintf(1, "cdb_delete(%d): %s\n", cdb,
640 static DBC *localcursor(int cdb)
645 if (MYCURSORS[cdb] == NULL)
646 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &curs, 0);
648 ret = MYCURSORS[cdb]->c_dup(MYCURSORS[cdb], &curs, DB_POSITION);
652 lprintf(1, "localcursor: %s\n", db_strerror(ret));
661 * Fetch a piece of data. If not found, returns NULL. Otherwise, it returns
662 * a struct cdbdata which it is the caller's responsibility to free later on
663 * using the cdb_free() routine.
665 struct cdbdata *cdb_fetch(int cdb, void *key, int keylen)
668 struct cdbdata *tempcdb;
672 memset(&dkey, 0, sizeof(DBT));
678 memset(&dret, 0, sizeof(DBT));
679 dret.flags = DB_DBT_MALLOC;
680 ret = dbp[cdb]->get(dbp[cdb], MYTID, &dkey, &dret, 0);
688 memset(&dret, 0, sizeof(DBT));
689 dret.flags = DB_DBT_MALLOC;
691 curs = localcursor(cdb);
693 ret = curs->c_get(curs, &dkey, &dret, DB_SET);
696 while (ret == DB_LOCK_DEADLOCK);
700 if ((ret != 0) && (ret != DB_NOTFOUND))
702 lprintf(1, "cdb_fetch(%d): %s\n", cdb, db_strerror(ret));
706 if (ret != 0) return NULL;
707 tempcdb = (struct cdbdata *) mallok(sizeof(struct cdbdata));
711 lprintf(2, "cdb_fetch: Cannot allocate memory for tempcdb\n");
715 tempcdb->len = dret.size;
716 tempcdb->ptr = dret.data;
718 cdb_decompress_if_necessary(tempcdb);
725 * Free a cdbdata item (ok, this is really no big deal, but we might need to do
726 * more complex stuff with other database managers in the future).
728 void cdb_free(struct cdbdata *cdb)
734 void cdb_close_cursor(int cdb)
736 if (MYCURSORS[cdb] != NULL)
737 cclose(MYCURSORS[cdb]);
739 MYCURSORS[cdb] = NULL;
743 * Prepare for a sequential search of an entire database.
744 * (There is guaranteed to be no more than one traversal in
745 * progress per thread at any given time.)
747 void cdb_rewind(int cdb)
751 if (MYCURSORS[cdb] != NULL)
752 cclose(MYCURSORS[cdb]);
755 * Now initialize the cursor
757 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &MYCURSORS[cdb], 0);
759 lprintf(1, "cdb_rewind: db_cursor: %s\n", db_strerror(ret));
766 * Fetch the next item in a sequential search. Returns a pointer to a
767 * cdbdata structure, or NULL if we've hit the end.
769 struct cdbdata *cdb_next_item(int cdb)
772 struct cdbdata *cdbret;
775 /* Initialize the key/data pair so the flags aren't set. */
776 memset(&key, 0, sizeof(key));
777 memset(&data, 0, sizeof(data));
778 data.flags = DB_DBT_MALLOC;
780 ret = MYCURSORS[cdb]->c_get(MYCURSORS[cdb],
781 &key, &data, DB_NEXT);
784 if (ret != DB_NOTFOUND) {
785 lprintf(1, "cdb_next_item(%d): %s\n",
786 cdb, db_strerror(ret));
789 cclose(MYCURSORS[cdb]);
790 MYCURSORS[cdb] = NULL;
791 return NULL; /* presumably, end of file */
794 cdbret = (struct cdbdata *) mallok(sizeof(struct cdbdata));
795 cdbret->len = data.size;
796 cdbret->ptr = data.data;
798 cdb_decompress_if_necessary(cdbret);
807 * Transaction-based stuff. I'm writing this as I bake cookies...
810 void cdb_begin_transaction(void) {
812 bailIfCursor(MYCURSORS, "can't begin transaction during r/o cursor");
816 lprintf(1, "cdb_begin_transaction: ERROR: nested transaction\n");
823 void cdb_end_transaction(void) {
826 for (i = 0; i < MAXCDB; i++)
827 if (MYCURSORS[i] != NULL) {
828 lprintf(1, "cdb_end_transaction: WARNING: cursor %d still open at transaction end\n", i);
829 cclose(MYCURSORS[i]);
835 lprintf(1, "cdb_end_transaction: ERROR: txcommit(NULL) !!\n");
845 * Truncate (delete every record)
847 void cdb_trunc(int cdb)
851 #if DB_VERSION_MAJOR > 3 || DB_VERSION_MINOR > 2
857 lprintf(1, "cdb_trunc must not be called in a transaction.\n");
862 bailIfCursor(MYCURSORS, "attempt to write during r/o cursor");
864 #if DB_VERSION_MAJOR == 3 && DB_VERSION_MINOR < 3
869 /* Initialize the key/data pair so the flags aren't set. */
870 memset(&key, 0, sizeof(key));
871 memset(&data, 0, sizeof(data));
875 ret = dbp[cdb]->cursor(dbp[cdb], tid, &MYCURSORS[cdb], 0);
878 lprintf(1, "cdb_trunc: db_cursor: %s\n", db_strerror(ret));
882 ret = MYCURSORS[cdb]->c_get(MYCURSORS[cdb],
883 &key, &data, DB_NEXT);
886 cclose(MYCURSORS[cdb]);
888 if (ret == DB_LOCK_DEADLOCK)
891 if (ret == DB_NOTFOUND)
894 lprintf(1, "cdb_trunc: c_get: %s\n", db_strerror(ret));
898 ret = MYCURSORS[cdb]->c_del(MYCURSORS[cdb], 0);
901 cclose(MYCURSORS[cdb]);
903 if (ret == DB_LOCK_DEADLOCK)
906 lprintf(1, "cdb_trunc: c_del: %s\n", db_strerror(ret));
910 cclose(MYCURSORS[cdb]);
917 if ((ret = dbp[cdb]->truncate(dbp[cdb], /* db */
918 tid, /* transaction ID */
919 &count, /* #rows deleted */
922 if (ret == DB_LOCK_DEADLOCK)
929 lprintf(1, "cdb_truncate(%d): %s\n", cdb,