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(1, "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(1, "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(1, "cdb_*: txn_begin: %s\n", db_strerror(ret));
112 static void cclose(DBC *cursor) {
115 if ((ret = cursor->c_close(cursor))) {
116 lprintf(1, "cdb_*: c_close: %s\n", db_strerror(ret));
121 static void bailIfCursor(DBC **cursors, const char *msg)
125 for (i = 0; i < MAXCDB; i++)
126 if (cursors[i] != NULL)
128 lprintf(1, "cdb_*: cursor still in progress on cdb %d: %s\n", i, msg);
133 static void check_handles(void *arg) {
135 struct cdbtsd *tsd = (struct cdbtsd *)arg;
137 bailIfCursor(tsd->cursors, "in check_handles");
139 if (tsd->tid != NULL) {
140 lprintf(1, "cdb_*: transaction still in progress!");
146 static void dest_tsd(void *arg) {
154 * Ensure that we have a key for thread-specific data. We don't
155 * put anything in here that Citadel cares about; this is just database
156 * related stuff like cursors and transactions.
158 * This should be called immediately after startup by any thread which wants
159 * to use database calls, except for whatever thread calls open_databases.
161 void cdb_allocate_tsd(void) {
164 if (pthread_getspecific(tsdkey) != NULL)
167 tsd = mallok(sizeof(struct cdbtsd));
171 memset(tsd->cursors, 0, sizeof tsd->cursors);
172 pthread_setspecific(tsdkey, tsd);
175 void cdb_free_tsd(void) {
176 dest_tsd(pthread_getspecific(tsdkey));
177 pthread_setspecific(tsdkey, NULL);
180 void cdb_check_handles(void) {
181 check_handles(pthread_getspecific(tsdkey));
186 * Reclaim unused space in the databases. We need to do each one of
187 * these discretely, rather than in a loop.
189 * This is a stub function in the Sleepycat DB backend, because there is no
190 * such API call available.
192 void defrag_databases(void)
199 * Cull the database logs
201 static void cdb_cull_logs(void) {
207 lprintf(5, "Database log file cull started.\n");
211 /* Get the list of names. */
212 if ((ret = dbenv->log_archive(dbenv, &list, flags)) != 0) {
213 lprintf(1, "cdb_cull_logs: %s\n", db_strerror(ret));
217 /* Print the list of names. */
219 for (file = list; *file != NULL; ++file) {
220 lprintf(9, "Deleting log: %s\n", *file);
223 snprintf(errmsg, sizeof(errmsg),
224 " ** ERROR **\n \n \n "
225 "Citadel was unable to delete the "
226 "database log file '%s' because of the "
227 "following error:\n \n %s\n \n"
228 " This log file is no longer in use "
229 "and may be safely deleted.\n",
232 aide_message(errmsg);
238 lprintf(5, "Database log file cull ended.\n");
243 * Request a checkpoint of the database.
245 static void cdb_checkpoint(void) {
247 static time_t last_cull = 0L;
249 ret = dbenv->txn_checkpoint(dbenv,
250 MAX_CHECKPOINT_KBYTES,
251 MAX_CHECKPOINT_MINUTES,
255 lprintf(1, "cdb_checkpoint: txn_checkpoint: %s\n",
260 /* Cull the logs if we haven't done so for 24 hours */
261 if ((time(NULL) - last_cull) > 86400L) {
262 last_cull = time(NULL);
269 * Open the various databases we'll be using. Any database which
270 * does not exist should be created. Note that we don't need an S_DATABASE
271 * critical section here, because there aren't any active threads manipulating
272 * the database yet -- and besides, it causes problems on BSDI.
274 void open_databases(void)
278 char dbfilename[SIZ];
281 lprintf(9, "cdb_*: open_databases() starting\n");
282 lprintf(5, "%s\n", db_version(NULL, NULL, NULL));
284 lprintf(5, "zlib compression version %s\n", zlibVersion());
288 * Silently try to create the database subdirectory. If it's
289 * already there, no problem.
291 system("exec mkdir data 2>/dev/null");
293 lprintf(9, "cdb_*: Setting up DB environment\n");
294 db_env_set_func_yield(sched_yield);
295 ret = db_env_create(&dbenv, 0);
297 lprintf(1, "cdb_*: db_env_create: %s\n", db_strerror(ret));
300 dbenv->set_errpfx(dbenv, "citserver");
303 * We want to specify the shared memory buffer pool cachesize,
304 * but everything else is the default.
306 ret = dbenv->set_cachesize(dbenv, 0, 64 * 1024, 0);
308 lprintf(1, "cdb_*: set_cachesize: %s\n", db_strerror(ret));
309 dbenv->close(dbenv, 0);
313 if ((ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT))) {
314 lprintf(1, "cdb_*: set_lk_detect: %s\n", db_strerror(ret));
315 dbenv->close(dbenv, 0);
319 flags = DB_CREATE|DB_RECOVER|DB_INIT_MPOOL|DB_PRIVATE|DB_INIT_TXN|
320 DB_INIT_LOCK|DB_THREAD;
321 ret = dbenv->open(dbenv, "./data", flags, 0);
323 lprintf(1, "cdb_*: dbenv->open: %s\n", db_strerror(ret));
324 dbenv->close(dbenv, 0);
328 lprintf(7, "cdb_*: Starting up DB\n");
330 for (i = 0; i < MAXCDB; ++i) {
332 /* Create a database handle */
333 ret = db_create(&dbp[i], dbenv, 0);
335 lprintf(1, "cdb_*: db_create: %s\n", db_strerror(ret));
340 /* Arbitrary names for our tables -- we reference them by
341 * number, so we don't have string names for them.
343 snprintf(dbfilename, sizeof dbfilename, "cdb.%02x", i);
345 ret = dbp[i]->open(dbp[i],
355 lprintf(1, "cdb_*: db_open[%d]: %s\n", i, db_strerror(ret));
360 if ((ret = pthread_key_create(&tsdkey, dest_tsd))) {
361 lprintf(1, "cdb_*: pthread_key_create: %s\n", strerror(ret));
366 CtdlRegisterSessionHook(cdb_checkpoint, EVT_TIMER);
367 lprintf(9, "cdb_*: open_databases() finished\n");
372 * Close all of the db database files we've opened. This can be done
373 * in a loop, since it's just a bunch of closes.
375 void close_databases(void)
382 if ((ret = dbenv->txn_checkpoint(dbenv, 0, 0, 0))) {
383 lprintf(1, "cdb_*: txn_checkpoint: %s\n", db_strerror(ret));
387 for (a = 0; a < MAXCDB; ++a) {
388 lprintf(7, "cdb_*: Closing database %d\n", a);
389 ret = dbp[a]->close(dbp[a], 0);
391 lprintf(1, "cdb_*: db_close: %s\n", db_strerror(ret));
397 /* Close the handle. */
398 ret = dbenv->close(dbenv, 0);
400 lprintf(1, "cdb_*: DBENV->close: %s\n", db_strerror(ret));
407 * Compression functions only used if we have zlib
411 void cdb_decompress_if_necessary(struct cdbdata *cdb) {
412 static int magic = COMPRESS_MAGIC;
413 struct CtdlCompressHeader zheader;
414 char *uncompressed_data;
415 char *compressed_data;
416 uLongf destLen, sourceLen;
418 if (cdb == NULL) return;
419 if (cdb->ptr == NULL) return;
420 if (memcmp(cdb->ptr, &magic, sizeof(magic))) return;
422 /* At this point we know we're looking at a compressed item. */
423 memcpy(&zheader, cdb->ptr, sizeof(struct CtdlCompressHeader));
425 compressed_data = cdb->ptr;
426 compressed_data += sizeof(struct CtdlCompressHeader);
428 sourceLen = (uLongf) zheader.compressed_len;
429 destLen = (uLongf) zheader.uncompressed_len;
430 uncompressed_data = mallok(zheader.uncompressed_len);
432 if (uncompress( (Bytef *) uncompressed_data,
437 lprintf(1, "uncompress() error\n");
442 cdb->len = (size_t) destLen;
443 cdb->ptr = uncompressed_data;
446 #endif /* HAVE_ZLIB */
450 * Store a piece of data. Returns 0 if the operation was successful. If a
451 * key already exists it should be overwritten.
453 int cdb_store(int cdb,
454 void *ckey, int ckeylen,
455 void *cdata, int cdatalen)
463 struct CtdlCompressHeader zheader;
464 char *compressed_data = NULL;
470 memset(&dkey, 0, sizeof(DBT));
471 memset(&ddata, 0, sizeof(DBT));
474 ddata.size = cdatalen;
478 /* Only compress Visit records. Everything else is uncompressed. */
479 if (cdb == CDB_VISIT) {
481 zheader.magic = COMPRESS_MAGIC;
482 zheader.uncompressed_len = cdatalen;
483 buffer_len = ( (cdatalen * 101) / 100 ) + 100
484 + sizeof(struct CtdlCompressHeader) ;
485 destLen = (uLongf) buffer_len;
486 compressed_data = mallok(buffer_len);
488 (Bytef *) (compressed_data +
489 sizeof(struct CtdlCompressHeader)),
495 lprintf(1, "compress2() error\n");
498 zheader.compressed_len = (size_t) destLen;
499 memcpy(compressed_data, &zheader,
500 sizeof(struct CtdlCompressHeader));
501 ddata.size = (size_t) (sizeof(struct CtdlCompressHeader) +
502 zheader.compressed_len);
503 ddata.data = compressed_data;
509 ret = dbp[cdb]->put(dbp[cdb], /* db */
510 MYTID, /* transaction ID */
516 lprintf(1, "cdb_store(%d): %s\n", cdb,
521 if (compressing) phree(compressed_data);
528 bailIfCursor(MYCURSORS, "attempt to write during r/o cursor");
533 if ((ret = dbp[cdb]->put(dbp[cdb], /* db */
534 tid, /* transaction ID */
539 if (ret == DB_LOCK_DEADLOCK)
546 lprintf(1, "cdb_store(%d): %s\n", cdb,
555 if (compressing) phree(compressed_data);
564 * Delete a piece of data. Returns 0 if the operation was successful.
566 int cdb_delete(int cdb, void *key, int keylen)
573 memset(&dkey, 0, sizeof dkey);
579 ret = dbp[cdb]->del(dbp[cdb], MYTID, &dkey, 0);
582 lprintf(1, "cdb_delete(%d): %s\n", cdb,
584 if (ret != DB_NOTFOUND)
590 bailIfCursor(MYCURSORS, "attempt to delete during r/o cursor");
595 if ((ret = dbp[cdb]->del(dbp[cdb], tid, &dkey, 0))
596 && ret != DB_NOTFOUND)
598 if (ret == DB_LOCK_DEADLOCK)
605 lprintf(1, "cdb_delete(%d): %s\n", cdb,
618 static DBC *localcursor(int cdb)
623 if (MYCURSORS[cdb] == NULL)
624 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &curs, 0);
626 ret = MYCURSORS[cdb]->c_dup(MYCURSORS[cdb], &curs, DB_POSITION);
630 lprintf(1, "localcursor: %s\n", db_strerror(ret));
639 * Fetch a piece of data. If not found, returns NULL. Otherwise, it returns
640 * a struct cdbdata which it is the caller's responsibility to free later on
641 * using the cdb_free() routine.
643 struct cdbdata *cdb_fetch(int cdb, void *key, int keylen)
646 struct cdbdata *tempcdb;
650 memset(&dkey, 0, sizeof(DBT));
656 memset(&dret, 0, sizeof(DBT));
657 dret.flags = DB_DBT_MALLOC;
658 ret = dbp[cdb]->get(dbp[cdb], MYTID, &dkey, &dret, 0);
666 memset(&dret, 0, sizeof(DBT));
667 dret.flags = DB_DBT_MALLOC;
669 curs = localcursor(cdb);
671 ret = curs->c_get(curs, &dkey, &dret, DB_SET);
674 while (ret == DB_LOCK_DEADLOCK);
678 if ((ret != 0) && (ret != DB_NOTFOUND))
680 lprintf(1, "cdb_fetch(%d): %s\n", cdb, db_strerror(ret));
684 if (ret != 0) return NULL;
685 tempcdb = (struct cdbdata *) mallok(sizeof(struct cdbdata));
689 lprintf(2, "cdb_fetch: Cannot allocate memory for tempcdb\n");
693 tempcdb->len = dret.size;
694 tempcdb->ptr = dret.data;
696 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;
776 cdb_decompress_if_necessary(cdbret);
785 * Transaction-based stuff. I'm writing this as I bake cookies...
788 void cdb_begin_transaction(void) {
790 bailIfCursor(MYCURSORS, "can't begin transaction during r/o cursor");
794 lprintf(1, "cdb_begin_transaction: ERROR: nested transaction\n");
801 void cdb_end_transaction(void) {
804 for (i = 0; i < MAXCDB; i++)
805 if (MYCURSORS[i] != NULL) {
806 lprintf(1, "cdb_end_transaction: WARNING: cursor %d still open at transaction end\n", i);
807 cclose(MYCURSORS[i]);
813 lprintf(1, "cdb_end_transaction: ERROR: txcommit(NULL) !!\n");
823 * Truncate (delete every record)
825 void cdb_trunc(int cdb)
833 lprintf(1, "cdb_trunc must not be called in a transaction.\n");
838 bailIfCursor(MYCURSORS, "attempt to write during r/o cursor");
843 if ((ret = dbp[cdb]->truncate(dbp[cdb], /* db */
844 tid, /* transaction ID */
845 &count, /* #rows deleted */
848 if (ret == DB_LOCK_DEADLOCK)
855 lprintf(1, "cdb_truncate(%d): %s\n", cdb,