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"
60 static DB *dbp[MAXCDB]; /* One DB handle for each Citadel database */
61 static DB_ENV *dbenv; /* The DB environment (global) */
63 struct cdbtsd { /* Thread-specific DB stuff */
64 DB_TXN *tid; /* Transaction handle */
65 DBC *cursors[MAXCDB]; /* Cursors, for traversals... */
72 static pthread_key_t tsdkey;
74 #define MYCURSORS (((struct cdbtsd*)pthread_getspecific(tsdkey))->cursors)
75 #define MYTID (((struct cdbtsd*)pthread_getspecific(tsdkey))->tid)
77 /* just a little helper function */
78 static void txabort(DB_TXN *tid) {
81 ret = tid->abort(tid);
84 lprintf(CTDL_EMERG, "cdb_*: txn_abort: %s\n", db_strerror(ret));
89 /* this one is even more helpful than the last. */
90 static void txcommit(DB_TXN *tid) {
93 ret = tid->commit(tid, 0);
96 lprintf(CTDL_EMERG, "cdb_*: txn_commit: %s\n", db_strerror(ret));
101 /* are you sensing a pattern yet? */
102 static void txbegin(DB_TXN **tid) {
105 ret = dbenv->txn_begin(dbenv, NULL, tid, 0);
108 lprintf(CTDL_EMERG, "cdb_*: txn_begin: %s\n", db_strerror(ret));
113 static void dbpanic(DB_ENV* env, int errval)
115 lprintf(CTDL_EMERG, "cdb_*: Berkeley DB panic: %d\n", errval);
118 static void cclose(DBC *cursor) {
121 if ((ret = cursor->c_close(cursor))) {
122 lprintf(CTDL_EMERG, "cdb_*: c_close: %s\n", db_strerror(ret));
127 static void bailIfCursor(DBC **cursors, const char *msg)
131 for (i = 0; i < MAXCDB; i++)
132 if (cursors[i] != NULL)
134 lprintf(CTDL_EMERG, "cdb_*: cursor still in progress on cdb %d: %s\n", i, msg);
139 static void check_handles(void *arg) {
141 struct cdbtsd *tsd = (struct cdbtsd *)arg;
143 bailIfCursor(tsd->cursors, "in check_handles");
145 if (tsd->tid != NULL) {
146 lprintf(CTDL_EMERG, "cdb_*: transaction still in progress!");
152 static void dest_tsd(void *arg) {
160 * Ensure that we have a key for thread-specific data. We don't
161 * put anything in here that Citadel cares about; this is just database
162 * related stuff like cursors and transactions.
164 * This should be called immediately after startup by any thread which wants
165 * to use database calls, except for whatever thread calls open_databases.
167 void cdb_allocate_tsd(void) {
170 if (pthread_getspecific(tsdkey) != NULL)
173 tsd = malloc(sizeof(struct cdbtsd));
177 memset(tsd->cursors, 0, sizeof tsd->cursors);
178 pthread_setspecific(tsdkey, tsd);
181 void cdb_free_tsd(void) {
182 dest_tsd(pthread_getspecific(tsdkey));
183 pthread_setspecific(tsdkey, NULL);
186 void cdb_check_handles(void) {
187 check_handles(pthread_getspecific(tsdkey));
192 * Reclaim unused space in the databases. We need to do each one of
193 * these discretely, rather than in a loop.
195 * This is a stub function in the Sleepycat DB backend, because there is no
196 * such API call available.
198 void defrag_databases(void)
205 * Cull the database logs
207 static void cdb_cull_logs(void) {
213 lprintf(CTDL_INFO, "Database log file cull started.\n");
217 /* Get the list of names. */
218 if ((ret = dbenv->log_archive(dbenv, &list, flags)) != 0) {
219 lprintf(CTDL_ERR, "cdb_cull_logs: %s\n", db_strerror(ret));
223 /* Print the list of names. */
225 for (file = list; *file != NULL; ++file) {
226 lprintf(CTDL_DEBUG, "Deleting log: %s\n", *file);
229 snprintf(errmsg, sizeof(errmsg),
230 " ** ERROR **\n \n \n "
231 "Citadel was unable to delete the "
232 "database log file '%s' because of the "
233 "following error:\n \n %s\n \n"
234 " This log file is no longer in use "
235 "and may be safely deleted.\n",
238 aide_message(errmsg);
244 lprintf(CTDL_INFO, "Database log file cull ended.\n");
249 * Request a checkpoint of the database.
251 static void cdb_checkpoint(void) {
253 static time_t last_cull = 0L;
255 ret = dbenv->txn_checkpoint(dbenv,
256 MAX_CHECKPOINT_KBYTES,
257 MAX_CHECKPOINT_MINUTES,
261 lprintf(CTDL_EMERG, "cdb_checkpoint: txn_checkpoint: %s\n",
266 /* Cull the logs if we haven't done so for 24 hours */
267 if ((time(NULL) - last_cull) > 86400L) {
268 last_cull = time(NULL);
275 * Open the various databases we'll be using. Any database which
276 * does not exist should be created. Note that we don't need an S_DATABASE
277 * critical section here, because there aren't any active threads manipulating
278 * the database yet -- and besides, it causes problems on BSDI.
280 void open_databases(void)
284 char dbfilename[SIZ];
286 char dbdirname[PATH_MAX];
289 char filename[PATH_MAX];
292 getcwd(dbdirname, sizeof dbdirname);
293 strcat(dbdirname, "/data");
295 lprintf(CTDL_DEBUG, "cdb_*: open_databases() starting\n");
296 lprintf(CTDL_DEBUG, "Compiled db: %s\n", DB_VERSION_STRING);
297 lprintf(CTDL_INFO, " Linked db: %s\n", db_version(NULL, NULL, NULL));
299 lprintf(CTDL_INFO, "Linked zlib: %s\n", zlibVersion());
303 * Silently try to create the database subdirectory. If it's
304 * already there, no problem.
306 mkdir(dbdirname, 0700);
307 chmod(dbdirname, 0700);
308 chown(dbdirname, BBSUID, (-1) );
310 lprintf(CTDL_DEBUG, "cdb_*: Setting up DB environment\n");
311 db_env_set_func_yield(sched_yield);
312 ret = db_env_create(&dbenv, 0);
314 lprintf(CTDL_EMERG, "cdb_*: db_env_create: %s\n", db_strerror(ret));
317 dbenv->set_errpfx(dbenv, "citserver");
318 dbenv->set_paniccall(dbenv, dbpanic);
321 * We want to specify the shared memory buffer pool cachesize,
322 * but everything else is the default.
324 ret = dbenv->set_cachesize(dbenv, 0, 64 * 1024, 0);
326 lprintf(CTDL_EMERG, "cdb_*: set_cachesize: %s\n", db_strerror(ret));
327 dbenv->close(dbenv, 0);
331 if ((ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT))) {
332 lprintf(CTDL_EMERG, "cdb_*: set_lk_detect: %s\n", db_strerror(ret));
333 dbenv->close(dbenv, 0);
337 flags = DB_CREATE|DB_RECOVER|DB_INIT_MPOOL|DB_PRIVATE|DB_INIT_TXN|
338 DB_INIT_LOCK|DB_THREAD;
339 lprintf(CTDL_DEBUG, "dbenv->open(dbenv, %s, %d, 0)\n", dbdirname, flags);
340 ret = dbenv->open(dbenv, dbdirname, flags, 0);
342 lprintf(CTDL_DEBUG, "cdb_*: dbenv->open: %s\n", db_strerror(ret));
343 dbenv->close(dbenv, 0);
347 lprintf(CTDL_INFO, "cdb_*: Starting up DB\n");
349 for (i = 0; i < MAXCDB; ++i) {
351 /* Create a database handle */
352 ret = db_create(&dbp[i], dbenv, 0);
354 lprintf(CTDL_DEBUG, "cdb_*: db_create: %s\n", db_strerror(ret));
359 /* Arbitrary names for our tables -- we reference them by
360 * number, so we don't have string names for them.
362 snprintf(dbfilename, sizeof dbfilename, "cdb.%02x", i);
364 ret = dbp[i]->open(dbp[i],
374 lprintf(CTDL_EMERG, "cdb_*: db_open[%d]: %s\n", i, db_strerror(ret));
379 if ((ret = pthread_key_create(&tsdkey, dest_tsd))) {
380 lprintf(CTDL_EMERG, "cdb_*: pthread_key_create: %s\n", strerror(ret));
385 CtdlRegisterSessionHook(cdb_checkpoint, EVT_TIMER);
387 /* Now make sure we own all the files, because in a few milliseconds
388 * we're going to drop root privs.
390 dp = opendir(dbdirname);
392 while (d = readdir(dp), d != NULL) {
393 if (d->d_name[0] != '.') {
394 snprintf(filename, sizeof filename, "%s/%s",
395 dbdirname, d->d_name);
396 chmod(filename, 0600);
397 chown(filename, BBSUID, (-1) );
403 lprintf(CTDL_DEBUG, "cdb_*: open_databases() finished\n");
408 * Close all of the db database files we've opened. This can be done
409 * in a loop, since it's just a bunch of closes.
411 void close_databases(void)
418 if ((ret = dbenv->txn_checkpoint(dbenv, 0, 0, 0))) {
419 lprintf(CTDL_EMERG, "cdb_*: txn_checkpoint: %s\n", db_strerror(ret));
423 for (a = 0; a < MAXCDB; ++a) {
424 lprintf(CTDL_INFO, "cdb_*: Closing database %d\n", a);
425 ret = dbp[a]->close(dbp[a], 0);
427 lprintf(CTDL_EMERG, "cdb_*: db_close: %s\n", db_strerror(ret));
433 /* Close the handle. */
434 ret = dbenv->close(dbenv, 0);
436 lprintf(CTDL_EMERG, "cdb_*: DBENV->close: %s\n", db_strerror(ret));
443 * Compression functions only used if we have zlib
447 void cdb_decompress_if_necessary(struct cdbdata *cdb) {
448 static int magic = COMPRESS_MAGIC;
449 struct CtdlCompressHeader zheader;
450 char *uncompressed_data;
451 char *compressed_data;
452 uLongf destLen, sourceLen;
454 if (cdb == NULL) return;
455 if (cdb->ptr == NULL) return;
456 if (memcmp(cdb->ptr, &magic, sizeof(magic))) return;
458 /* At this point we know we're looking at a compressed item. */
459 memcpy(&zheader, cdb->ptr, sizeof(struct CtdlCompressHeader));
461 compressed_data = cdb->ptr;
462 compressed_data += sizeof(struct CtdlCompressHeader);
464 sourceLen = (uLongf) zheader.compressed_len;
465 destLen = (uLongf) zheader.uncompressed_len;
466 uncompressed_data = malloc(zheader.uncompressed_len);
468 if (uncompress( (Bytef *) uncompressed_data,
473 lprintf(CTDL_EMERG, "uncompress() error\n");
478 cdb->len = (size_t) destLen;
479 cdb->ptr = uncompressed_data;
482 #endif /* HAVE_ZLIB */
486 * Store a piece of data. Returns 0 if the operation was successful. If a
487 * key already exists it should be overwritten.
489 int cdb_store(int cdb,
490 void *ckey, int ckeylen,
491 void *cdata, int cdatalen)
499 struct CtdlCompressHeader zheader;
500 char *compressed_data = NULL;
506 memset(&dkey, 0, sizeof(DBT));
507 memset(&ddata, 0, sizeof(DBT));
510 ddata.size = cdatalen;
514 /* Only compress Visit records. Everything else is uncompressed. */
515 if (cdb == CDB_VISIT) {
517 zheader.magic = COMPRESS_MAGIC;
518 zheader.uncompressed_len = cdatalen;
519 buffer_len = ( (cdatalen * 101) / 100 ) + 100
520 + sizeof(struct CtdlCompressHeader) ;
521 destLen = (uLongf) buffer_len;
522 compressed_data = malloc(buffer_len);
524 (Bytef *) (compressed_data +
525 sizeof(struct CtdlCompressHeader)),
531 lprintf(CTDL_EMERG, "compress2() error\n");
534 zheader.compressed_len = (size_t) destLen;
535 memcpy(compressed_data, &zheader,
536 sizeof(struct CtdlCompressHeader));
537 ddata.size = (size_t) (sizeof(struct CtdlCompressHeader) +
538 zheader.compressed_len);
539 ddata.data = compressed_data;
545 ret = dbp[cdb]->put(dbp[cdb], /* db */
546 MYTID, /* transaction ID */
552 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n", cdb, db_strerror(ret));
556 if (compressing) free(compressed_data);
563 bailIfCursor(MYCURSORS, "attempt to write during r/o cursor");
568 if ((ret = dbp[cdb]->put(dbp[cdb], /* db */
569 tid, /* transaction ID */
574 if (ret == DB_LOCK_DEADLOCK)
581 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n", cdb, db_strerror(ret));
589 if (compressing) free(compressed_data);
598 * Delete a piece of data. Returns 0 if the operation was successful.
600 int cdb_delete(int cdb, void *key, int keylen)
607 memset(&dkey, 0, sizeof dkey);
613 ret = dbp[cdb]->del(dbp[cdb], MYTID, &dkey, 0);
616 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n", cdb, db_strerror(ret));
617 if (ret != DB_NOTFOUND)
623 bailIfCursor(MYCURSORS, "attempt to delete during r/o cursor");
628 if ((ret = dbp[cdb]->del(dbp[cdb], tid, &dkey, 0))
629 && ret != DB_NOTFOUND)
631 if (ret == DB_LOCK_DEADLOCK)
638 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n", cdb, db_strerror(ret));
650 static DBC *localcursor(int cdb)
655 if (MYCURSORS[cdb] == NULL)
656 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &curs, 0);
658 ret = MYCURSORS[cdb]->c_dup(MYCURSORS[cdb], &curs, DB_POSITION);
662 lprintf(CTDL_EMERG, "localcursor: %s\n", db_strerror(ret));
671 * Fetch a piece of data. If not found, returns NULL. Otherwise, it returns
672 * a struct cdbdata which it is the caller's responsibility to free later on
673 * using the cdb_free() routine.
675 struct cdbdata *cdb_fetch(int cdb, void *key, int keylen)
678 struct cdbdata *tempcdb;
682 memset(&dkey, 0, sizeof(DBT));
688 memset(&dret, 0, sizeof(DBT));
689 dret.flags = DB_DBT_MALLOC;
690 ret = dbp[cdb]->get(dbp[cdb], MYTID, &dkey, &dret, 0);
698 memset(&dret, 0, sizeof(DBT));
699 dret.flags = DB_DBT_MALLOC;
701 curs = localcursor(cdb);
703 ret = curs->c_get(curs, &dkey, &dret, DB_SET);
706 while (ret == DB_LOCK_DEADLOCK);
710 if ((ret != 0) && (ret != DB_NOTFOUND))
712 lprintf(CTDL_EMERG, "cdb_fetch(%d): %s\n", cdb, db_strerror(ret));
716 if (ret != 0) return NULL;
717 tempcdb = (struct cdbdata *) malloc(sizeof(struct cdbdata));
721 lprintf(CTDL_EMERG, "cdb_fetch: Cannot allocate memory for tempcdb\n");
725 tempcdb->len = dret.size;
726 tempcdb->ptr = dret.data;
728 cdb_decompress_if_necessary(tempcdb);
735 * Free a cdbdata item (ok, this is really no big deal, but we might need to do
736 * more complex stuff with other database managers in the future).
738 void cdb_free(struct cdbdata *cdb)
744 void cdb_close_cursor(int cdb)
746 if (MYCURSORS[cdb] != NULL)
747 cclose(MYCURSORS[cdb]);
749 MYCURSORS[cdb] = NULL;
753 * Prepare for a sequential search of an entire database.
754 * (There is guaranteed to be no more than one traversal in
755 * progress per thread at any given time.)
757 void cdb_rewind(int cdb)
761 if (MYCURSORS[cdb] != NULL)
762 cclose(MYCURSORS[cdb]);
765 * Now initialize the cursor
767 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &MYCURSORS[cdb], 0);
769 lprintf(CTDL_EMERG, "cdb_rewind: db_cursor: %s\n", db_strerror(ret));
776 * Fetch the next item in a sequential search. Returns a pointer to a
777 * cdbdata structure, or NULL if we've hit the end.
779 struct cdbdata *cdb_next_item(int cdb)
782 struct cdbdata *cdbret;
785 /* Initialize the key/data pair so the flags aren't set. */
786 memset(&key, 0, sizeof(key));
787 memset(&data, 0, sizeof(data));
788 data.flags = DB_DBT_MALLOC;
790 ret = MYCURSORS[cdb]->c_get(MYCURSORS[cdb],
791 &key, &data, DB_NEXT);
794 if (ret != DB_NOTFOUND) {
795 lprintf(CTDL_EMERG, "cdb_next_item(%d): %s\n",
796 cdb, db_strerror(ret));
799 cclose(MYCURSORS[cdb]);
800 MYCURSORS[cdb] = NULL;
801 return NULL; /* presumably, end of file */
804 cdbret = (struct cdbdata *) malloc(sizeof(struct cdbdata));
805 cdbret->len = data.size;
806 cdbret->ptr = data.data;
808 cdb_decompress_if_necessary(cdbret);
817 * Transaction-based stuff. I'm writing this as I bake cookies...
820 void cdb_begin_transaction(void) {
822 bailIfCursor(MYCURSORS, "can't begin transaction during r/o cursor");
826 lprintf(CTDL_EMERG, "cdb_begin_transaction: ERROR: nested transaction\n");
833 void cdb_end_transaction(void) {
836 for (i = 0; i < MAXCDB; i++)
837 if (MYCURSORS[i] != NULL) {
838 lprintf(CTDL_WARNING, "cdb_end_transaction: WARNING: cursor %d still open at transaction end\n", i);
839 cclose(MYCURSORS[i]);
845 lprintf(CTDL_EMERG, "cdb_end_transaction: ERROR: txcommit(NULL) !!\n");
855 * Truncate (delete every record)
857 void cdb_trunc(int cdb)
865 lprintf(CTDL_EMERG, "cdb_trunc must not be called in a transaction.\n");
870 bailIfCursor(MYCURSORS, "attempt to write during r/o cursor");
875 if ((ret = dbp[cdb]->truncate(dbp[cdb], /* db */
876 tid, /* transaction ID */
877 &count, /* #rows deleted */
880 if (ret == DB_LOCK_DEADLOCK)
887 lprintf(CTDL_EMERG, "cdb_truncate(%d): %s\n", cdb, db_strerror(ret));