4 * Sleepycat (Berkeley) DB driver for Citadel
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"
61 static DB *dbp[MAXCDB]; /* One DB handle for each Citadel database */
62 static DB_ENV *dbenv; /* The DB environment (global) */
64 struct cdbtsd { /* Thread-specific DB stuff */
65 DB_TXN *tid; /* Transaction handle */
66 DBC *cursors[MAXCDB]; /* Cursors, for traversals... */
73 static pthread_key_t tsdkey;
75 #define MYCURSORS (((struct cdbtsd*)pthread_getspecific(tsdkey))->cursors)
76 #define MYTID (((struct cdbtsd*)pthread_getspecific(tsdkey))->tid)
78 /* just a little helper function */
79 static void txabort(DB_TXN *tid) {
82 ret = tid->abort(tid);
85 lprintf(CTDL_EMERG, "cdb_*: txn_abort: %s\n", db_strerror(ret));
90 /* this one is even more helpful than the last. */
91 static void txcommit(DB_TXN *tid) {
94 ret = tid->commit(tid, 0);
97 lprintf(CTDL_EMERG, "cdb_*: txn_commit: %s\n", db_strerror(ret));
102 /* are you sensing a pattern yet? */
103 static void txbegin(DB_TXN **tid) {
106 ret = dbenv->txn_begin(dbenv, NULL, tid, 0);
109 lprintf(CTDL_EMERG, "cdb_*: txn_begin: %s\n", db_strerror(ret));
114 static void dbpanic(DB_ENV* env, int errval)
116 lprintf(CTDL_EMERG, "cdb_*: Berkeley DB panic: %d\n", errval);
119 static void cclose(DBC *cursor) {
122 if ((ret = cursor->c_close(cursor))) {
123 lprintf(CTDL_EMERG, "cdb_*: c_close: %s\n", db_strerror(ret));
128 static void bailIfCursor(DBC **cursors, const char *msg)
132 for (i = 0; i < MAXCDB; i++)
133 if (cursors[i] != NULL)
135 lprintf(CTDL_EMERG, "cdb_*: cursor still in progress on cdb %d: %s\n", i, msg);
140 static void check_handles(void *arg) {
142 struct cdbtsd *tsd = (struct cdbtsd *)arg;
144 bailIfCursor(tsd->cursors, "in check_handles");
146 if (tsd->tid != NULL) {
147 lprintf(CTDL_EMERG, "cdb_*: transaction still in progress!");
153 static void dest_tsd(void *arg) {
161 * Ensure that we have a key for thread-specific data. We don't
162 * put anything in here that Citadel cares about; this is just database
163 * related stuff like cursors and transactions.
165 * This should be called immediately after startup by any thread which wants
166 * to use database calls, except for whatever thread calls open_databases.
168 void cdb_allocate_tsd(void) {
171 if (pthread_getspecific(tsdkey) != NULL)
174 tsd = malloc(sizeof(struct cdbtsd));
178 memset(tsd->cursors, 0, sizeof tsd->cursors);
179 pthread_setspecific(tsdkey, tsd);
182 void cdb_free_tsd(void) {
183 dest_tsd(pthread_getspecific(tsdkey));
184 pthread_setspecific(tsdkey, NULL);
187 void cdb_check_handles(void) {
188 check_handles(pthread_getspecific(tsdkey));
193 * Reclaim unused space in the databases. We need to do each one of
194 * these discretely, rather than in a loop.
196 * This is a stub function in the Sleepycat DB backend, because there is no
197 * such API call available.
199 void defrag_databases(void)
206 * Cull the database logs
208 static void cdb_cull_logs(void) {
214 lprintf(CTDL_INFO, "Database log file cull started.\n");
218 /* Get the list of names. */
219 if ((ret = dbenv->log_archive(dbenv, &list, flags)) != 0) {
220 lprintf(CTDL_ERR, "cdb_cull_logs: %s\n", db_strerror(ret));
224 /* Print the list of names. */
226 for (file = list; *file != NULL; ++file) {
227 lprintf(CTDL_DEBUG, "Deleting log: %s\n", *file);
230 snprintf(errmsg, sizeof(errmsg),
231 " ** ERROR **\n \n \n "
232 "Citadel was unable to delete the "
233 "database log file '%s' because of the "
234 "following error:\n \n %s\n \n"
235 " This log file is no longer in use "
236 "and may be safely deleted.\n",
239 aide_message(errmsg);
245 lprintf(CTDL_INFO, "Database log file cull ended.\n");
250 * Request a checkpoint of the database.
252 static void cdb_checkpoint(void) {
254 static time_t last_cull = 0L;
256 ret = dbenv->txn_checkpoint(dbenv,
257 MAX_CHECKPOINT_KBYTES,
258 MAX_CHECKPOINT_MINUTES,
262 lprintf(CTDL_EMERG, "cdb_checkpoint: txn_checkpoint: %s\n",
267 /* Cull the logs if we haven't done so for 24 hours */
268 if ((time(NULL) - last_cull) > 86400L) {
269 last_cull = time(NULL);
276 * Open the various databases we'll be using. Any database which
277 * does not exist should be created. Note that we don't need a
278 * critical section here, because there aren't any active threads
279 * manipulating the database yet.
281 void open_databases(void)
285 char dbfilename[SIZ];
287 char dbdirname[PATH_MAX];
288 char dblogname[PATH_MAX];
291 char filename[PATH_MAX];
294 getcwd(dbdirname, sizeof dbdirname);
295 strcat(dbdirname, "/data");
296 getcwd(dblogname, sizeof dblogname);
297 strcat(dblogname, "/data_logs");
299 lprintf(CTDL_DEBUG, "cdb_*: open_databases() starting\n");
300 lprintf(CTDL_DEBUG, "Compiled db: %s\n", DB_VERSION_STRING);
301 lprintf(CTDL_INFO, " Linked db: %s\n", db_version(NULL, NULL, NULL));
303 lprintf(CTDL_INFO, "Linked zlib: %s\n", zlibVersion());
307 * Silently try to create the database subdirectory. If it's
308 * already there, no problem.
310 mkdir(dbdirname, 0700);
311 chmod(dbdirname, 0700);
312 chown(dbdirname, BBSUID, (-1) );
315 * By default, keep database logs in the same directory. A savvy
316 * system administrator will know what to do if he/she wants to put
319 symlink("data", dblogname);
321 lprintf(CTDL_DEBUG, "cdb_*: Setting up DB environment\n");
322 db_env_set_func_yield(sched_yield);
323 ret = db_env_create(&dbenv, 0);
325 lprintf(CTDL_EMERG, "cdb_*: db_env_create: %s\n", db_strerror(ret));
328 dbenv->set_errpfx(dbenv, "citserver");
329 dbenv->set_paniccall(dbenv, dbpanic);
332 * We want to specify the shared memory buffer pool cachesize,
333 * but everything else is the default.
335 ret = dbenv->set_cachesize(dbenv, 0, 64 * 1024, 0);
337 lprintf(CTDL_EMERG, "cdb_*: set_cachesize: %s\n", db_strerror(ret));
338 dbenv->close(dbenv, 0);
342 if ((ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT))) {
343 lprintf(CTDL_EMERG, "cdb_*: set_lk_detect: %s\n", db_strerror(ret));
344 dbenv->close(dbenv, 0);
348 if ((ret = dbenv->set_data_dir(dbenv, dbdirname))) {
349 lprintf(CTDL_EMERG, "cdb_*: set_data_dir: %s\n", db_strerror(ret));
350 dbenv->close(dbenv, 0);
354 if ((ret = dbenv->set_lg_dir(dbenv, dblogname))) {
355 lprintf(CTDL_EMERG, "cdb_*: set_lg_dir: %s\n", db_strerror(ret));
356 dbenv->close(dbenv, 0);
360 flags = DB_CREATE|DB_RECOVER|DB_INIT_MPOOL|DB_PRIVATE|DB_INIT_TXN|
361 DB_INIT_LOCK|DB_THREAD;
362 lprintf(CTDL_DEBUG, "dbenv->open(dbenv, NULL, %d, 0)\n", flags);
363 ret = dbenv->open(dbenv, NULL, flags, 0);
365 lprintf(CTDL_DEBUG, "cdb_*: dbenv->open: %s\n", db_strerror(ret));
366 dbenv->close(dbenv, 0);
370 lprintf(CTDL_INFO, "cdb_*: Starting up DB\n");
372 for (i = 0; i < MAXCDB; ++i) {
374 /* Create a database handle */
375 ret = db_create(&dbp[i], dbenv, 0);
377 lprintf(CTDL_DEBUG, "cdb_*: db_create: %s\n", db_strerror(ret));
382 /* Arbitrary names for our tables -- we reference them by
383 * number, so we don't have string names for them.
385 snprintf(dbfilename, sizeof dbfilename, "cdb.%02x", i);
387 ret = dbp[i]->open(dbp[i],
392 DB_CREATE|DB_AUTO_COMMIT|DB_THREAD
396 lprintf(CTDL_EMERG, "cdb_*: db_open[%d]: %s\n", i, db_strerror(ret));
401 if ((ret = pthread_key_create(&tsdkey, dest_tsd))) {
402 lprintf(CTDL_EMERG, "cdb_*: pthread_key_create: %s\n", strerror(ret));
407 CtdlRegisterSessionHook(cdb_checkpoint, EVT_TIMER);
409 /* Now make sure we own all the files, because in a few milliseconds
410 * we're going to drop root privs.
412 dp = opendir(dbdirname);
414 while (d = readdir(dp), d != NULL) {
415 if (d->d_name[0] != '.') {
416 snprintf(filename, sizeof filename, "%s/%s",
417 dbdirname, d->d_name);
418 chmod(filename, 0600);
419 chown(filename, BBSUID, (-1) );
425 lprintf(CTDL_DEBUG, "cdb_*: open_databases() finished\n");
430 * Close all of the db database files we've opened. This can be done
431 * in a loop, since it's just a bunch of closes.
433 void close_databases(void)
440 if ((ret = dbenv->txn_checkpoint(dbenv, 0, 0, 0))) {
442 "cdb_*: txn_checkpoint: %s\n",
446 for (a = 0; a < MAXCDB; ++a) {
447 lprintf(CTDL_INFO, "cdb_*: Closing database %d\n", a);
448 ret = dbp[a]->close(dbp[a], 0);
451 "cdb_*: db_close: %s\n",
457 /* Close the handle. */
458 ret = dbenv->close(dbenv, 0);
461 "cdb_*: DBENV->close: %s\n",
468 * Compression functions only used if we have zlib
472 void cdb_decompress_if_necessary(struct cdbdata *cdb) {
473 static int magic = COMPRESS_MAGIC;
474 struct CtdlCompressHeader zheader;
475 char *uncompressed_data;
476 char *compressed_data;
477 uLongf destLen, sourceLen;
479 if (cdb == NULL) return;
480 if (cdb->ptr == NULL) return;
481 if (memcmp(cdb->ptr, &magic, sizeof(magic))) return;
483 /* At this point we know we're looking at a compressed item. */
484 memcpy(&zheader, cdb->ptr, sizeof(struct CtdlCompressHeader));
486 compressed_data = cdb->ptr;
487 compressed_data += sizeof(struct CtdlCompressHeader);
489 sourceLen = (uLongf) zheader.compressed_len;
490 destLen = (uLongf) zheader.uncompressed_len;
491 uncompressed_data = malloc(zheader.uncompressed_len);
493 if (uncompress( (Bytef *) uncompressed_data,
495 (const Bytef *)compressed_data,
498 lprintf(CTDL_EMERG, "uncompress() error\n");
503 cdb->len = (size_t) destLen;
504 cdb->ptr = uncompressed_data;
507 #endif /* HAVE_ZLIB */
511 * Store a piece of data. Returns 0 if the operation was successful. If a
512 * key already exists it should be overwritten.
514 int cdb_store(int cdb,
515 void *ckey, int ckeylen,
516 void *cdata, int cdatalen)
524 struct CtdlCompressHeader zheader;
525 char *compressed_data = NULL;
531 memset(&dkey, 0, sizeof(DBT));
532 memset(&ddata, 0, sizeof(DBT));
535 ddata.size = cdatalen;
539 /* Only compress Visit records. Everything else is uncompressed. */
540 if (cdb == CDB_VISIT) {
542 zheader.magic = COMPRESS_MAGIC;
543 zheader.uncompressed_len = cdatalen;
544 buffer_len = ( (cdatalen * 101) / 100 ) + 100
545 + sizeof(struct CtdlCompressHeader) ;
546 destLen = (uLongf) buffer_len;
547 compressed_data = malloc(buffer_len);
549 (Bytef *) (compressed_data +
550 sizeof(struct CtdlCompressHeader)),
556 lprintf(CTDL_EMERG, "compress2() error\n");
559 zheader.compressed_len = (size_t) destLen;
560 memcpy(compressed_data, &zheader,
561 sizeof(struct CtdlCompressHeader));
562 ddata.size = (size_t) (sizeof(struct CtdlCompressHeader) +
563 zheader.compressed_len);
564 ddata.data = compressed_data;
570 ret = dbp[cdb]->put(dbp[cdb], /* db */
571 MYTID, /* transaction ID */
577 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n", cdb, db_strerror(ret));
581 if (compressing) free(compressed_data);
588 bailIfCursor(MYCURSORS, "attempt to write during r/o cursor");
593 if ((ret = dbp[cdb]->put(dbp[cdb], /* db */
594 tid, /* transaction ID */
599 if (ret == DB_LOCK_DEADLOCK)
606 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n", cdb, db_strerror(ret));
614 if (compressing) free(compressed_data);
623 * Delete a piece of data. Returns 0 if the operation was successful.
625 int cdb_delete(int cdb, void *key, int keylen)
632 memset(&dkey, 0, sizeof dkey);
638 ret = dbp[cdb]->del(dbp[cdb], MYTID, &dkey, 0);
641 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n", cdb, db_strerror(ret));
642 if (ret != DB_NOTFOUND)
648 bailIfCursor(MYCURSORS, "attempt to delete during r/o cursor");
653 if ((ret = dbp[cdb]->del(dbp[cdb], tid, &dkey, 0))
654 && ret != DB_NOTFOUND)
656 if (ret == DB_LOCK_DEADLOCK)
663 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n", cdb, db_strerror(ret));
675 static DBC *localcursor(int cdb)
680 if (MYCURSORS[cdb] == NULL)
681 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &curs, 0);
683 ret = MYCURSORS[cdb]->c_dup(MYCURSORS[cdb], &curs, DB_POSITION);
687 lprintf(CTDL_EMERG, "localcursor: %s\n", db_strerror(ret));
696 * Fetch a piece of data. If not found, returns NULL. Otherwise, it returns
697 * a struct cdbdata which it is the caller's responsibility to free later on
698 * using the cdb_free() routine.
700 struct cdbdata *cdb_fetch(int cdb, void *key, int keylen)
703 struct cdbdata *tempcdb;
707 memset(&dkey, 0, sizeof(DBT));
713 memset(&dret, 0, sizeof(DBT));
714 dret.flags = DB_DBT_MALLOC;
715 ret = dbp[cdb]->get(dbp[cdb], MYTID, &dkey, &dret, 0);
723 memset(&dret, 0, sizeof(DBT));
724 dret.flags = DB_DBT_MALLOC;
726 curs = localcursor(cdb);
728 ret = curs->c_get(curs, &dkey, &dret, DB_SET);
731 while (ret == DB_LOCK_DEADLOCK);
735 if ((ret != 0) && (ret != DB_NOTFOUND))
737 lprintf(CTDL_EMERG, "cdb_fetch(%d): %s\n", cdb, db_strerror(ret));
741 if (ret != 0) return NULL;
742 tempcdb = (struct cdbdata *) malloc(sizeof(struct cdbdata));
746 lprintf(CTDL_EMERG, "cdb_fetch: Cannot allocate memory for tempcdb\n");
750 tempcdb->len = dret.size;
751 tempcdb->ptr = dret.data;
753 cdb_decompress_if_necessary(tempcdb);
760 * Free a cdbdata item (ok, this is really no big deal, but we might need to do
761 * more complex stuff with other database managers in the future).
763 void cdb_free(struct cdbdata *cdb)
769 void cdb_close_cursor(int cdb)
771 if (MYCURSORS[cdb] != NULL)
772 cclose(MYCURSORS[cdb]);
774 MYCURSORS[cdb] = NULL;
778 * Prepare for a sequential search of an entire database.
779 * (There is guaranteed to be no more than one traversal in
780 * progress per thread at any given time.)
782 void cdb_rewind(int cdb)
786 if (MYCURSORS[cdb] != NULL) {
787 lprintf(CTDL_EMERG, "cdb_rewind: must close cursor on database %d before reopening.\n", cdb);
789 /* cclose(MYCURSORS[cdb]); */
793 * Now initialize the cursor
795 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &MYCURSORS[cdb], 0);
797 lprintf(CTDL_EMERG, "cdb_rewind: db_cursor: %s\n", db_strerror(ret));
804 * Fetch the next item in a sequential search. Returns a pointer to a
805 * cdbdata structure, or NULL if we've hit the end.
807 struct cdbdata *cdb_next_item(int cdb)
810 struct cdbdata *cdbret;
813 /* Initialize the key/data pair so the flags aren't set. */
814 memset(&key, 0, sizeof(key));
815 memset(&data, 0, sizeof(data));
816 data.flags = DB_DBT_MALLOC;
818 ret = MYCURSORS[cdb]->c_get(MYCURSORS[cdb],
819 &key, &data, DB_NEXT);
822 if (ret != DB_NOTFOUND) {
823 lprintf(CTDL_EMERG, "cdb_next_item(%d): %s\n",
824 cdb, db_strerror(ret));
827 cclose(MYCURSORS[cdb]);
828 MYCURSORS[cdb] = NULL;
829 return NULL; /* presumably, end of file */
832 cdbret = (struct cdbdata *) malloc(sizeof(struct cdbdata));
833 cdbret->len = data.size;
834 cdbret->ptr = data.data;
836 cdb_decompress_if_necessary(cdbret);
845 * Transaction-based stuff. I'm writing this as I bake cookies...
848 void cdb_begin_transaction(void) {
850 bailIfCursor(MYCURSORS, "can't begin transaction during r/o cursor");
854 lprintf(CTDL_EMERG, "cdb_begin_transaction: ERROR: nested transaction\n");
861 void cdb_end_transaction(void) {
864 for (i = 0; i < MAXCDB; i++)
865 if (MYCURSORS[i] != NULL) {
866 lprintf(CTDL_WARNING, "cdb_end_transaction: WARNING: cursor %d still open at transaction end\n", i);
867 cclose(MYCURSORS[i]);
873 lprintf(CTDL_EMERG, "cdb_end_transaction: ERROR: txcommit(NULL) !!\n");
883 * Truncate (delete every record)
885 void cdb_trunc(int cdb)
893 lprintf(CTDL_EMERG, "cdb_trunc must not be called in a transaction.\n");
898 bailIfCursor(MYCURSORS, "attempt to write during r/o cursor");
903 if ((ret = dbp[cdb]->truncate(dbp[cdb], /* db */
904 tid, /* transaction ID */
905 &count, /* #rows deleted */
908 if (ret == DB_LOCK_DEADLOCK)
915 lprintf(CTDL_EMERG, "cdb_truncate(%d): %s\n", cdb, db_strerror(ret));