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"
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) {
215 /* Get the list of names. */
216 if ((ret = dbenv->log_archive(dbenv, &list, flags)) != 0) {
217 lprintf(CTDL_ERR, "cdb_cull_logs: %s\n", db_strerror(ret));
221 /* Print the list of names. */
223 for (file = list; *file != NULL; ++file) {
224 lprintf(CTDL_DEBUG, "Deleting log: %s\n", *file);
227 snprintf(errmsg, sizeof(errmsg),
228 " ** ERROR **\n \n \n "
229 "Citadel was unable to delete the "
230 "database log file '%s' because of the "
231 "following error:\n \n %s\n \n"
232 " This log file is no longer in use "
233 "and may be safely deleted.\n",
236 aide_message(errmsg);
242 lprintf(CTDL_INFO, "Database log file cull ended.\n");
247 * Request a checkpoint of the database.
249 static void cdb_checkpoint(void) {
251 /* static time_t last_cull = 0L; */
253 ret = dbenv->txn_checkpoint(dbenv,
254 MAX_CHECKPOINT_KBYTES,
255 MAX_CHECKPOINT_MINUTES,
259 lprintf(CTDL_EMERG, "cdb_checkpoint: txn_checkpoint: %s\n",
264 /* After a successful checkpoint, we can cull the unused logs */
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];
290 char filename[PATH_MAX];
293 getcwd(dbdirname, sizeof dbdirname);
294 strcat(dbdirname, "/data");
296 lprintf(CTDL_DEBUG, "cdb_*: open_databases() starting\n");
297 lprintf(CTDL_DEBUG, "Compiled db: %s\n", DB_VERSION_STRING);
298 lprintf(CTDL_INFO, " Linked db: %s\n", db_version(NULL, NULL, NULL));
300 lprintf(CTDL_INFO, "Linked zlib: %s\n", zlibVersion());
304 * Silently try to create the database subdirectory. If it's
305 * already there, no problem.
307 mkdir(dbdirname, 0700);
308 chmod(dbdirname, 0700);
309 chown(dbdirname, CTDLUID, (-1) );
311 lprintf(CTDL_DEBUG, "cdb_*: Setting up DB environment\n");
312 db_env_set_func_yield(sched_yield);
313 ret = db_env_create(&dbenv, 0);
315 lprintf(CTDL_EMERG, "cdb_*: db_env_create: %s\n", db_strerror(ret));
318 dbenv->set_errpfx(dbenv, "citserver");
319 dbenv->set_paniccall(dbenv, dbpanic);
322 * We want to specify the shared memory buffer pool cachesize,
323 * but everything else is the default.
325 ret = dbenv->set_cachesize(dbenv, 0, 64 * 1024, 0);
327 lprintf(CTDL_EMERG, "cdb_*: set_cachesize: %s\n", db_strerror(ret));
328 dbenv->close(dbenv, 0);
332 if ((ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT))) {
333 lprintf(CTDL_EMERG, "cdb_*: set_lk_detect: %s\n", db_strerror(ret));
334 dbenv->close(dbenv, 0);
338 flags = DB_CREATE|DB_RECOVER|DB_INIT_MPOOL|DB_PRIVATE|DB_INIT_TXN|
339 DB_INIT_LOCK|DB_THREAD;
340 lprintf(CTDL_DEBUG, "dbenv->open(dbenv, %s, %d, 0)\n", dbdirname, flags);
341 ret = dbenv->open(dbenv, dbdirname, flags, 0);
343 lprintf(CTDL_DEBUG, "cdb_*: dbenv->open: %s\n", db_strerror(ret));
344 dbenv->close(dbenv, 0);
348 lprintf(CTDL_INFO, "cdb_*: Starting up DB\n");
350 for (i = 0; i < MAXCDB; ++i) {
352 /* Create a database handle */
353 ret = db_create(&dbp[i], dbenv, 0);
355 lprintf(CTDL_DEBUG, "cdb_*: db_create: %s\n", db_strerror(ret));
360 /* Arbitrary names for our tables -- we reference them by
361 * number, so we don't have string names for them.
363 snprintf(dbfilename, sizeof dbfilename, "cdb.%02x", i);
365 ret = dbp[i]->open(dbp[i],
370 DB_CREATE|DB_AUTO_COMMIT|DB_THREAD
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, CTDLUID, (-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))) {
420 "cdb_*: txn_checkpoint: %s\n",
424 for (a = 0; a < MAXCDB; ++a) {
425 lprintf(CTDL_INFO, "cdb_*: Closing database %d\n", a);
426 ret = dbp[a]->close(dbp[a], 0);
429 "cdb_*: db_close: %s\n",
435 /* Close the handle. */
436 ret = dbenv->close(dbenv, 0);
439 "cdb_*: DBENV->close: %s\n",
446 * Compression functions only used if we have zlib
450 void cdb_decompress_if_necessary(struct cdbdata *cdb) {
451 static int magic = COMPRESS_MAGIC;
452 struct CtdlCompressHeader zheader;
453 char *uncompressed_data;
454 char *compressed_data;
455 uLongf destLen, sourceLen;
457 if (cdb == NULL) return;
458 if (cdb->ptr == NULL) return;
459 if (memcmp(cdb->ptr, &magic, sizeof(magic))) return;
461 /* At this point we know we're looking at a compressed item. */
462 memcpy(&zheader, cdb->ptr, sizeof(struct CtdlCompressHeader));
464 compressed_data = cdb->ptr;
465 compressed_data += sizeof(struct CtdlCompressHeader);
467 sourceLen = (uLongf) zheader.compressed_len;
468 destLen = (uLongf) zheader.uncompressed_len;
469 uncompressed_data = malloc(zheader.uncompressed_len);
471 if (uncompress( (Bytef *) uncompressed_data,
473 (const Bytef *)compressed_data,
476 lprintf(CTDL_EMERG, "uncompress() error\n");
481 cdb->len = (size_t) destLen;
482 cdb->ptr = uncompressed_data;
485 #endif /* HAVE_ZLIB */
489 * Store a piece of data. Returns 0 if the operation was successful. If a
490 * key already exists it should be overwritten.
492 int cdb_store(int cdb,
493 void *ckey, int ckeylen,
494 void *cdata, int cdatalen)
502 struct CtdlCompressHeader zheader;
503 char *compressed_data = NULL;
509 memset(&dkey, 0, sizeof(DBT));
510 memset(&ddata, 0, sizeof(DBT));
513 ddata.size = cdatalen;
517 /* Only compress Visit records. Everything else is uncompressed. */
518 if (cdb == CDB_VISIT) {
520 zheader.magic = COMPRESS_MAGIC;
521 zheader.uncompressed_len = cdatalen;
522 buffer_len = ( (cdatalen * 101) / 100 ) + 100
523 + sizeof(struct CtdlCompressHeader) ;
524 destLen = (uLongf) buffer_len;
525 compressed_data = malloc(buffer_len);
527 (Bytef *) (compressed_data +
528 sizeof(struct CtdlCompressHeader)),
534 lprintf(CTDL_EMERG, "compress2() error\n");
537 zheader.compressed_len = (size_t) destLen;
538 memcpy(compressed_data, &zheader,
539 sizeof(struct CtdlCompressHeader));
540 ddata.size = (size_t) (sizeof(struct CtdlCompressHeader) +
541 zheader.compressed_len);
542 ddata.data = compressed_data;
548 ret = dbp[cdb]->put(dbp[cdb], /* db */
549 MYTID, /* transaction ID */
555 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n", cdb, db_strerror(ret));
559 if (compressing) free(compressed_data);
566 bailIfCursor(MYCURSORS, "attempt to write during r/o cursor");
571 if ((ret = dbp[cdb]->put(dbp[cdb], /* db */
572 tid, /* transaction ID */
577 if (ret == DB_LOCK_DEADLOCK)
584 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n", cdb, db_strerror(ret));
592 if (compressing) free(compressed_data);
601 * Delete a piece of data. Returns 0 if the operation was successful.
603 int cdb_delete(int cdb, void *key, int keylen)
610 memset(&dkey, 0, sizeof dkey);
616 ret = dbp[cdb]->del(dbp[cdb], MYTID, &dkey, 0);
619 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n", cdb, db_strerror(ret));
620 if (ret != DB_NOTFOUND)
626 bailIfCursor(MYCURSORS, "attempt to delete during r/o cursor");
631 if ((ret = dbp[cdb]->del(dbp[cdb], tid, &dkey, 0))
632 && ret != DB_NOTFOUND)
634 if (ret == DB_LOCK_DEADLOCK)
641 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n", cdb, db_strerror(ret));
653 static DBC *localcursor(int cdb)
658 if (MYCURSORS[cdb] == NULL)
659 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &curs, 0);
661 ret = MYCURSORS[cdb]->c_dup(MYCURSORS[cdb], &curs, DB_POSITION);
665 lprintf(CTDL_EMERG, "localcursor: %s\n", db_strerror(ret));
674 * Fetch a piece of data. If not found, returns NULL. Otherwise, it returns
675 * a struct cdbdata which it is the caller's responsibility to free later on
676 * using the cdb_free() routine.
678 struct cdbdata *cdb_fetch(int cdb, void *key, int keylen)
681 struct cdbdata *tempcdb;
685 memset(&dkey, 0, sizeof(DBT));
691 memset(&dret, 0, sizeof(DBT));
692 dret.flags = DB_DBT_MALLOC;
693 ret = dbp[cdb]->get(dbp[cdb], MYTID, &dkey, &dret, 0);
701 memset(&dret, 0, sizeof(DBT));
702 dret.flags = DB_DBT_MALLOC;
704 curs = localcursor(cdb);
706 ret = curs->c_get(curs, &dkey, &dret, DB_SET);
709 while (ret == DB_LOCK_DEADLOCK);
713 if ((ret != 0) && (ret != DB_NOTFOUND))
715 lprintf(CTDL_EMERG, "cdb_fetch(%d): %s\n", cdb, db_strerror(ret));
719 if (ret != 0) return NULL;
720 tempcdb = (struct cdbdata *) malloc(sizeof(struct cdbdata));
724 lprintf(CTDL_EMERG, "cdb_fetch: Cannot allocate memory for tempcdb\n");
728 tempcdb->len = dret.size;
729 tempcdb->ptr = dret.data;
731 cdb_decompress_if_necessary(tempcdb);
738 * Free a cdbdata item (ok, this is really no big deal, but we might need to do
739 * more complex stuff with other database managers in the future).
741 void cdb_free(struct cdbdata *cdb)
747 void cdb_close_cursor(int cdb)
749 if (MYCURSORS[cdb] != NULL)
750 cclose(MYCURSORS[cdb]);
752 MYCURSORS[cdb] = NULL;
756 * Prepare for a sequential search of an entire database.
757 * (There is guaranteed to be no more than one traversal in
758 * progress per thread at any given time.)
760 void cdb_rewind(int cdb)
764 if (MYCURSORS[cdb] != NULL) {
765 lprintf(CTDL_EMERG, "cdb_rewind: must close cursor on database %d before reopening.\n", cdb);
767 /* cclose(MYCURSORS[cdb]); */
771 * Now initialize the cursor
773 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &MYCURSORS[cdb], 0);
775 lprintf(CTDL_EMERG, "cdb_rewind: db_cursor: %s\n", db_strerror(ret));
782 * Fetch the next item in a sequential search. Returns a pointer to a
783 * cdbdata structure, or NULL if we've hit the end.
785 struct cdbdata *cdb_next_item(int cdb)
788 struct cdbdata *cdbret;
791 /* Initialize the key/data pair so the flags aren't set. */
792 memset(&key, 0, sizeof(key));
793 memset(&data, 0, sizeof(data));
794 data.flags = DB_DBT_MALLOC;
796 ret = MYCURSORS[cdb]->c_get(MYCURSORS[cdb],
797 &key, &data, DB_NEXT);
800 if (ret != DB_NOTFOUND) {
801 lprintf(CTDL_EMERG, "cdb_next_item(%d): %s\n",
802 cdb, db_strerror(ret));
805 cclose(MYCURSORS[cdb]);
806 MYCURSORS[cdb] = NULL;
807 return NULL; /* presumably, end of file */
810 cdbret = (struct cdbdata *) malloc(sizeof(struct cdbdata));
811 cdbret->len = data.size;
812 cdbret->ptr = data.data;
814 cdb_decompress_if_necessary(cdbret);
823 * Transaction-based stuff. I'm writing this as I bake cookies...
826 void cdb_begin_transaction(void) {
828 bailIfCursor(MYCURSORS, "can't begin transaction during r/o cursor");
832 lprintf(CTDL_EMERG, "cdb_begin_transaction: ERROR: nested transaction\n");
839 void cdb_end_transaction(void) {
842 for (i = 0; i < MAXCDB; i++)
843 if (MYCURSORS[i] != NULL) {
844 lprintf(CTDL_WARNING, "cdb_end_transaction: WARNING: cursor %d still open at transaction end\n", i);
845 cclose(MYCURSORS[i]);
851 lprintf(CTDL_EMERG, "cdb_end_transaction: ERROR: txcommit(NULL) !!\n");
861 * Truncate (delete every record)
863 void cdb_trunc(int cdb)
871 lprintf(CTDL_EMERG, "cdb_trunc must not be called in a transaction.\n");
876 bailIfCursor(MYCURSORS, "attempt to write during r/o cursor");
881 if ((ret = dbp[cdb]->truncate(dbp[cdb], /* db */
882 tid, /* transaction ID */
883 &count, /* #rows deleted */
886 if (ret == DB_LOCK_DEADLOCK)
893 lprintf(CTDL_EMERG, "cdb_truncate(%d): %s\n", cdb, db_strerror(ret));