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) {
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 a
277 * critical section here, because there aren't any active threads
278 * manipulating the database yet.
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, CTDLUID, (-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],
369 DB_CREATE|DB_AUTO_COMMIT|DB_THREAD
373 lprintf(CTDL_EMERG, "cdb_*: db_open[%d]: %s\n", i, db_strerror(ret));
378 if ((ret = pthread_key_create(&tsdkey, dest_tsd))) {
379 lprintf(CTDL_EMERG, "cdb_*: pthread_key_create: %s\n", strerror(ret));
384 CtdlRegisterSessionHook(cdb_checkpoint, EVT_TIMER);
386 /* Now make sure we own all the files, because in a few milliseconds
387 * we're going to drop root privs.
389 dp = opendir(dbdirname);
391 while (d = readdir(dp), d != NULL) {
392 if (d->d_name[0] != '.') {
393 snprintf(filename, sizeof filename, "%s/%s",
394 dbdirname, d->d_name);
395 chmod(filename, 0600);
396 chown(filename, CTDLUID, (-1) );
402 lprintf(CTDL_DEBUG, "cdb_*: open_databases() finished\n");
407 * Close all of the db database files we've opened. This can be done
408 * in a loop, since it's just a bunch of closes.
410 void close_databases(void)
417 if ((ret = dbenv->txn_checkpoint(dbenv, 0, 0, 0))) {
419 "cdb_*: txn_checkpoint: %s\n",
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);
428 "cdb_*: db_close: %s\n",
434 /* Close the handle. */
435 ret = dbenv->close(dbenv, 0);
438 "cdb_*: DBENV->close: %s\n",
445 * Compression functions only used if we have zlib
449 void cdb_decompress_if_necessary(struct cdbdata *cdb) {
450 static int magic = COMPRESS_MAGIC;
451 struct CtdlCompressHeader zheader;
452 char *uncompressed_data;
453 char *compressed_data;
454 uLongf destLen, sourceLen;
456 if (cdb == NULL) return;
457 if (cdb->ptr == NULL) return;
458 if (memcmp(cdb->ptr, &magic, sizeof(magic))) return;
460 /* At this point we know we're looking at a compressed item. */
461 memcpy(&zheader, cdb->ptr, sizeof(struct CtdlCompressHeader));
463 compressed_data = cdb->ptr;
464 compressed_data += sizeof(struct CtdlCompressHeader);
466 sourceLen = (uLongf) zheader.compressed_len;
467 destLen = (uLongf) zheader.uncompressed_len;
468 uncompressed_data = malloc(zheader.uncompressed_len);
470 if (uncompress( (Bytef *) uncompressed_data,
472 (const Bytef *)compressed_data,
475 lprintf(CTDL_EMERG, "uncompress() error\n");
480 cdb->len = (size_t) destLen;
481 cdb->ptr = uncompressed_data;
484 #endif /* HAVE_ZLIB */
488 * Store a piece of data. Returns 0 if the operation was successful. If a
489 * key already exists it should be overwritten.
491 int cdb_store(int cdb,
492 void *ckey, int ckeylen,
493 void *cdata, int cdatalen)
501 struct CtdlCompressHeader zheader;
502 char *compressed_data = NULL;
508 memset(&dkey, 0, sizeof(DBT));
509 memset(&ddata, 0, sizeof(DBT));
512 ddata.size = cdatalen;
516 /* Only compress Visit records. Everything else is uncompressed. */
517 if (cdb == CDB_VISIT) {
519 zheader.magic = COMPRESS_MAGIC;
520 zheader.uncompressed_len = cdatalen;
521 buffer_len = ( (cdatalen * 101) / 100 ) + 100
522 + sizeof(struct CtdlCompressHeader) ;
523 destLen = (uLongf) buffer_len;
524 compressed_data = malloc(buffer_len);
526 (Bytef *) (compressed_data +
527 sizeof(struct CtdlCompressHeader)),
533 lprintf(CTDL_EMERG, "compress2() error\n");
536 zheader.compressed_len = (size_t) destLen;
537 memcpy(compressed_data, &zheader,
538 sizeof(struct CtdlCompressHeader));
539 ddata.size = (size_t) (sizeof(struct CtdlCompressHeader) +
540 zheader.compressed_len);
541 ddata.data = compressed_data;
547 ret = dbp[cdb]->put(dbp[cdb], /* db */
548 MYTID, /* transaction ID */
554 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n", cdb, db_strerror(ret));
558 if (compressing) free(compressed_data);
565 bailIfCursor(MYCURSORS, "attempt to write during r/o cursor");
570 if ((ret = dbp[cdb]->put(dbp[cdb], /* db */
571 tid, /* transaction ID */
576 if (ret == DB_LOCK_DEADLOCK)
583 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n", cdb, db_strerror(ret));
591 if (compressing) free(compressed_data);
600 * Delete a piece of data. Returns 0 if the operation was successful.
602 int cdb_delete(int cdb, void *key, int keylen)
609 memset(&dkey, 0, sizeof dkey);
615 ret = dbp[cdb]->del(dbp[cdb], MYTID, &dkey, 0);
618 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n", cdb, db_strerror(ret));
619 if (ret != DB_NOTFOUND)
625 bailIfCursor(MYCURSORS, "attempt to delete during r/o cursor");
630 if ((ret = dbp[cdb]->del(dbp[cdb], tid, &dkey, 0))
631 && ret != DB_NOTFOUND)
633 if (ret == DB_LOCK_DEADLOCK)
640 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n", cdb, db_strerror(ret));
652 static DBC *localcursor(int cdb)
657 if (MYCURSORS[cdb] == NULL)
658 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &curs, 0);
660 ret = MYCURSORS[cdb]->c_dup(MYCURSORS[cdb], &curs, DB_POSITION);
664 lprintf(CTDL_EMERG, "localcursor: %s\n", db_strerror(ret));
673 * Fetch a piece of data. If not found, returns NULL. Otherwise, it returns
674 * a struct cdbdata which it is the caller's responsibility to free later on
675 * using the cdb_free() routine.
677 struct cdbdata *cdb_fetch(int cdb, void *key, int keylen)
680 struct cdbdata *tempcdb;
684 memset(&dkey, 0, sizeof(DBT));
690 memset(&dret, 0, sizeof(DBT));
691 dret.flags = DB_DBT_MALLOC;
692 ret = dbp[cdb]->get(dbp[cdb], MYTID, &dkey, &dret, 0);
700 memset(&dret, 0, sizeof(DBT));
701 dret.flags = DB_DBT_MALLOC;
703 curs = localcursor(cdb);
705 ret = curs->c_get(curs, &dkey, &dret, DB_SET);
708 while (ret == DB_LOCK_DEADLOCK);
712 if ((ret != 0) && (ret != DB_NOTFOUND))
714 lprintf(CTDL_EMERG, "cdb_fetch(%d): %s\n", cdb, db_strerror(ret));
718 if (ret != 0) return NULL;
719 tempcdb = (struct cdbdata *) malloc(sizeof(struct cdbdata));
723 lprintf(CTDL_EMERG, "cdb_fetch: Cannot allocate memory for tempcdb\n");
727 tempcdb->len = dret.size;
728 tempcdb->ptr = dret.data;
730 cdb_decompress_if_necessary(tempcdb);
737 * Free a cdbdata item (ok, this is really no big deal, but we might need to do
738 * more complex stuff with other database managers in the future).
740 void cdb_free(struct cdbdata *cdb)
746 void cdb_close_cursor(int cdb)
748 if (MYCURSORS[cdb] != NULL)
749 cclose(MYCURSORS[cdb]);
751 MYCURSORS[cdb] = NULL;
755 * Prepare for a sequential search of an entire database.
756 * (There is guaranteed to be no more than one traversal in
757 * progress per thread at any given time.)
759 void cdb_rewind(int cdb)
763 if (MYCURSORS[cdb] != NULL) {
764 lprintf(CTDL_EMERG, "cdb_rewind: must close cursor on database %d before reopening.\n", cdb);
766 /* cclose(MYCURSORS[cdb]); */
770 * Now initialize the cursor
772 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &MYCURSORS[cdb], 0);
774 lprintf(CTDL_EMERG, "cdb_rewind: db_cursor: %s\n", db_strerror(ret));
781 * Fetch the next item in a sequential search. Returns a pointer to a
782 * cdbdata structure, or NULL if we've hit the end.
784 struct cdbdata *cdb_next_item(int cdb)
787 struct cdbdata *cdbret;
790 /* Initialize the key/data pair so the flags aren't set. */
791 memset(&key, 0, sizeof(key));
792 memset(&data, 0, sizeof(data));
793 data.flags = DB_DBT_MALLOC;
795 ret = MYCURSORS[cdb]->c_get(MYCURSORS[cdb],
796 &key, &data, DB_NEXT);
799 if (ret != DB_NOTFOUND) {
800 lprintf(CTDL_EMERG, "cdb_next_item(%d): %s\n",
801 cdb, db_strerror(ret));
804 cclose(MYCURSORS[cdb]);
805 MYCURSORS[cdb] = NULL;
806 return NULL; /* presumably, end of file */
809 cdbret = (struct cdbdata *) malloc(sizeof(struct cdbdata));
810 cdbret->len = data.size;
811 cdbret->ptr = data.data;
813 cdb_decompress_if_necessary(cdbret);
822 * Transaction-based stuff. I'm writing this as I bake cookies...
825 void cdb_begin_transaction(void) {
827 bailIfCursor(MYCURSORS, "can't begin transaction during r/o cursor");
831 lprintf(CTDL_EMERG, "cdb_begin_transaction: ERROR: nested transaction\n");
838 void cdb_end_transaction(void) {
841 for (i = 0; i < MAXCDB; i++)
842 if (MYCURSORS[i] != NULL) {
843 lprintf(CTDL_WARNING, "cdb_end_transaction: WARNING: cursor %d still open at transaction end\n", i);
844 cclose(MYCURSORS[i]);
850 lprintf(CTDL_EMERG, "cdb_end_transaction: ERROR: txcommit(NULL) !!\n");
860 * Truncate (delete every record)
862 void cdb_trunc(int cdb)
870 lprintf(CTDL_EMERG, "cdb_trunc must not be called in a transaction.\n");
875 bailIfCursor(MYCURSORS, "attempt to write during r/o cursor");
880 if ((ret = dbp[cdb]->truncate(dbp[cdb], /* db */
881 tid, /* transaction ID */
882 &count, /* #rows deleted */
885 if (ret == DB_LOCK_DEADLOCK)
892 lprintf(CTDL_EMERG, "cdb_truncate(%d): %s\n", cdb, db_strerror(ret));