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 /*****************************************************************************/
28 #include <sys/types.h>
34 #elif defined(HAVE_DB4_DB_H)
37 #error Neither <db.h> nor <db4/db.h> was found by configure. Install db4-devel.
41 #if DB_VERSION_MAJOR < 4 || DB_VERSION_MINOR < 1
42 #error Citadel requires Berkeley DB v4.1 or newer. Please upgrade.
49 #include "serv_extensions.h"
50 #include "citserver.h"
53 #include "sysdep_decls.h"
56 static DB *dbp[MAXCDB]; /* One DB handle for each Citadel database */
57 static DB_ENV *dbenv; /* The DB environment (global) */
59 struct cdbtsd { /* Thread-specific DB stuff */
60 DB_TXN *tid; /* Transaction handle */
61 DBC *cursors[MAXCDB]; /* Cursors, for traversals... */
68 static pthread_key_t tsdkey;
70 #define MYCURSORS (((struct cdbtsd*)pthread_getspecific(tsdkey))->cursors)
71 #define MYTID (((struct cdbtsd*)pthread_getspecific(tsdkey))->tid)
73 /* just a little helper function */
74 static void txabort(DB_TXN * tid)
78 ret = tid->abort(tid);
81 lprintf(CTDL_EMERG, "cdb_*: txn_abort: %s\n",
87 /* this one is even more helpful than the last. */
88 static void txcommit(DB_TXN * tid)
92 ret = tid->commit(tid, 0);
95 lprintf(CTDL_EMERG, "cdb_*: txn_commit: %s\n",
101 /* are you sensing a pattern yet? */
102 static void txbegin(DB_TXN ** tid)
106 ret = dbenv->txn_begin(dbenv, NULL, tid, 0);
109 lprintf(CTDL_EMERG, "cdb_*: txn_begin: %s\n",
115 static void dbpanic(DB_ENV * env, int errval)
117 lprintf(CTDL_EMERG, "cdb_*: Berkeley DB panic: %d\n", errval);
120 static void cclose(DBC * cursor)
124 if ((ret = cursor->c_close(cursor))) {
125 lprintf(CTDL_EMERG, "cdb_*: c_close: %s\n",
131 static void bailIfCursor(DBC ** cursors, const char *msg)
135 for (i = 0; i < MAXCDB; i++)
136 if (cursors[i] != NULL) {
138 "cdb_*: cursor still in progress on cdb %d: %s\n",
144 static void check_handles(void *arg)
147 struct cdbtsd *tsd = (struct cdbtsd *) arg;
149 bailIfCursor(tsd->cursors, "in check_handles");
151 if (tsd->tid != NULL) {
153 "cdb_*: transaction still in progress!");
159 static void dest_tsd(void *arg)
168 * Ensure that we have a key for thread-specific data. We don't
169 * put anything in here that Citadel cares about; this is just database
170 * related stuff like cursors and transactions.
172 * This should be called immediately after startup by any thread which wants
173 * to use database calls, except for whatever thread calls open_databases.
175 void cdb_allocate_tsd(void)
179 if (pthread_getspecific(tsdkey) != NULL)
182 tsd = malloc(sizeof(struct cdbtsd));
186 memset(tsd->cursors, 0, sizeof tsd->cursors);
187 pthread_setspecific(tsdkey, tsd);
190 void cdb_free_tsd(void)
192 dest_tsd(pthread_getspecific(tsdkey));
193 pthread_setspecific(tsdkey, NULL);
196 void cdb_check_handles(void)
198 check_handles(pthread_getspecific(tsdkey));
203 * Reclaim unused space in the databases. We need to do each one of
204 * these discretely, rather than in a loop.
206 * This is a stub function in the Sleepycat DB backend, because there is no
207 * such API call available.
209 void defrag_databases(void)
216 * Cull the database logs
218 static void cdb_cull_logs(void)
227 /* Get the list of names. */
228 if ((ret = dbenv->log_archive(dbenv, &list, flags)) != 0) {
229 lprintf(CTDL_ERR, "cdb_cull_logs: %s\n", db_strerror(ret));
233 /* Print the list of names. */
235 for (file = list; *file != NULL; ++file) {
236 lprintf(CTDL_DEBUG, "Deleting log: %s\n", *file);
239 snprintf(errmsg, sizeof(errmsg),
240 " ** ERROR **\n \n \n "
241 "Citadel was unable to delete the "
242 "database log file '%s' because of the "
243 "following error:\n \n %s\n \n"
244 " This log file is no longer in use "
245 "and may be safely deleted.\n",
246 *file, strerror(errno));
247 aide_message(errmsg);
255 * Manually initiate log file cull.
257 void cmd_cull(char *argbuf) {
258 if (CtdlAccessCheck(ac_internal)) return;
260 cprintf("%d Database log file cull completed.\n", CIT_OK);
265 * Request a checkpoint of the database.
267 static void cdb_checkpoint(void)
270 static time_t last_run = 0L;
272 /* Only do a checkpoint once per minute. */
273 if ((time(NULL) - last_run) < 60L) {
276 last_run = time(NULL);
278 lprintf(CTDL_DEBUG, "-- db checkpoint --\n");
279 ret = dbenv->txn_checkpoint(dbenv,
280 MAX_CHECKPOINT_KBYTES,
281 MAX_CHECKPOINT_MINUTES, 0);
284 lprintf(CTDL_EMERG, "cdb_checkpoint: txn_checkpoint: %s\n",
289 /* After a successful checkpoint, we can cull the unused logs */
290 if (config.c_auto_cull) {
297 * Main loop for the checkpoint thread.
299 void *checkpoint_thread(void *arg) {
300 struct CitContext checkpointCC;
302 lprintf(CTDL_DEBUG, "checkpoint_thread() initializing\n");
304 memset(&checkpointCC, 0, sizeof(struct CitContext));
305 checkpointCC.internal_pgm = 1;
306 checkpointCC.cs_pid = 0;
307 pthread_setspecific(MyConKey, (void *)&checkpointCC );
311 while (!time_to_die) {
316 lprintf(CTDL_DEBUG, "checkpoint_thread() exiting\n");
321 * Open the various databases we'll be using. Any database which
322 * does not exist should be created. Note that we don't need a
323 * critical section here, because there aren't any active threads
324 * manipulating the database yet.
326 void open_databases(void)
330 char dbfilename[SIZ];
332 char dbdirname[PATH_MAX];
335 char filename[PATH_MAX];
337 strcat(dbdirname,ctdl_data_dir);
339 lprintf(CTDL_DEBUG, "cdb_*: open_databases() starting\n");
340 lprintf(CTDL_DEBUG, "Compiled db: %s\n", DB_VERSION_STRING);
341 lprintf(CTDL_INFO, " Linked db: %s\n",
342 db_version(NULL, NULL, NULL));
344 lprintf(CTDL_INFO, "Linked zlib: %s\n", zlibVersion());
348 * Silently try to create the database subdirectory. If it's
349 * already there, no problem.
351 mkdir(dbdirname, 0700);
352 chmod(dbdirname, 0700);
353 chown(dbdirname, CTDLUID, (-1));
355 lprintf(CTDL_DEBUG, "cdb_*: Setting up DB environment\n");
356 db_env_set_func_yield(sched_yield);
357 ret = db_env_create(&dbenv, 0);
359 lprintf(CTDL_EMERG, "cdb_*: db_env_create: %s\n",
363 dbenv->set_errpfx(dbenv, "citserver");
364 dbenv->set_paniccall(dbenv, dbpanic);
367 * We want to specify the shared memory buffer pool cachesize,
368 * but everything else is the default.
370 ret = dbenv->set_cachesize(dbenv, 0, 64 * 1024, 0);
372 lprintf(CTDL_EMERG, "cdb_*: set_cachesize: %s\n",
374 dbenv->close(dbenv, 0);
378 if ((ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT))) {
379 lprintf(CTDL_EMERG, "cdb_*: set_lk_detect: %s\n",
381 dbenv->close(dbenv, 0);
386 DB_CREATE | DB_RECOVER | DB_INIT_MPOOL | DB_PRIVATE |
387 DB_INIT_TXN | DB_INIT_LOCK | DB_THREAD;
388 lprintf(CTDL_DEBUG, "dbenv->open(dbenv, %s, %d, 0)\n", dbdirname,
390 ret = dbenv->open(dbenv, dbdirname, flags, 0);
392 lprintf(CTDL_DEBUG, "cdb_*: dbenv->open: %s\n",
394 dbenv->close(dbenv, 0);
398 lprintf(CTDL_INFO, "cdb_*: Starting up DB\n");
400 for (i = 0; i < MAXCDB; ++i) {
402 /* Create a database handle */
403 ret = db_create(&dbp[i], dbenv, 0);
405 lprintf(CTDL_DEBUG, "cdb_*: db_create: %s\n",
411 /* Arbitrary names for our tables -- we reference them by
412 * number, so we don't have string names for them.
414 snprintf(dbfilename, sizeof dbfilename, "cdb.%02x", i);
416 ret = dbp[i]->open(dbp[i],
421 DB_CREATE | DB_AUTO_COMMIT | DB_THREAD,
424 lprintf(CTDL_EMERG, "cdb_*: db_open[%d]: %s\n", i,
430 if ((ret = pthread_key_create(&tsdkey, dest_tsd))) {
431 lprintf(CTDL_EMERG, "cdb_*: pthread_key_create: %s\n",
438 /* Now make sure we own all the files, because in a few milliseconds
439 * we're going to drop root privs.
441 dp = opendir(dbdirname);
443 while (d = readdir(dp), d != NULL) {
444 if (d->d_name[0] != '.') {
445 snprintf(filename, sizeof filename,
446 "%s/%s", dbdirname, d->d_name);
447 chmod(filename, 0600);
448 chown(filename, CTDLUID, (-1));
454 lprintf(CTDL_DEBUG, "cdb_*: open_databases() finished\n");
456 CtdlRegisterProtoHook(cmd_cull, "CULL", "Cull database logs");
461 * Close all of the db database files we've opened. This can be done
462 * in a loop, since it's just a bunch of closes.
464 void close_databases(void)
471 if ((ret = dbenv->txn_checkpoint(dbenv, 0, 0, 0))) {
473 "cdb_*: txn_checkpoint: %s\n", db_strerror(ret));
476 for (a = 0; a < MAXCDB; ++a) {
477 lprintf(CTDL_INFO, "cdb_*: Closing database %d\n", a);
478 ret = dbp[a]->close(dbp[a], 0);
481 "cdb_*: db_close: %s\n", db_strerror(ret));
486 /* Close the handle. */
487 ret = dbenv->close(dbenv, 0);
490 "cdb_*: DBENV->close: %s\n", db_strerror(ret));
496 * Compression functions only used if we have zlib
500 void cdb_decompress_if_necessary(struct cdbdata *cdb)
502 static int magic = COMPRESS_MAGIC;
503 struct CtdlCompressHeader zheader;
504 char *uncompressed_data;
505 char *compressed_data;
506 uLongf destLen, sourceLen;
510 if (cdb->ptr == NULL)
512 if (memcmp(cdb->ptr, &magic, sizeof(magic)))
515 /* At this point we know we're looking at a compressed item. */
516 memcpy(&zheader, cdb->ptr, sizeof(struct CtdlCompressHeader));
518 compressed_data = cdb->ptr;
519 compressed_data += sizeof(struct CtdlCompressHeader);
521 sourceLen = (uLongf) zheader.compressed_len;
522 destLen = (uLongf) zheader.uncompressed_len;
523 uncompressed_data = malloc(zheader.uncompressed_len);
525 if (uncompress((Bytef *) uncompressed_data,
526 (uLongf *) & destLen,
527 (const Bytef *) compressed_data,
528 (uLong) sourceLen) != Z_OK) {
529 lprintf(CTDL_EMERG, "uncompress() error\n");
534 cdb->len = (size_t) destLen;
535 cdb->ptr = uncompressed_data;
538 #endif /* HAVE_ZLIB */
542 * Store a piece of data. Returns 0 if the operation was successful. If a
543 * key already exists it should be overwritten.
545 int cdb_store(int cdb, void *ckey, int ckeylen, void *cdata, int cdatalen)
553 struct CtdlCompressHeader zheader;
554 char *compressed_data = NULL;
560 memset(&dkey, 0, sizeof(DBT));
561 memset(&ddata, 0, sizeof(DBT));
564 ddata.size = cdatalen;
568 /* Only compress Visit records. Everything else is uncompressed. */
569 if (cdb == CDB_VISIT) {
571 zheader.magic = COMPRESS_MAGIC;
572 zheader.uncompressed_len = cdatalen;
573 buffer_len = ((cdatalen * 101) / 100) + 100
574 + sizeof(struct CtdlCompressHeader);
575 destLen = (uLongf) buffer_len;
576 compressed_data = malloc(buffer_len);
577 if (compress2((Bytef *) (compressed_data +
579 CtdlCompressHeader)),
580 &destLen, (Bytef *) cdata, (uLongf) cdatalen,
582 lprintf(CTDL_EMERG, "compress2() error\n");
585 zheader.compressed_len = (size_t) destLen;
586 memcpy(compressed_data, &zheader,
587 sizeof(struct CtdlCompressHeader));
588 ddata.size = (size_t) (sizeof(struct CtdlCompressHeader) +
589 zheader.compressed_len);
590 ddata.data = compressed_data;
595 ret = dbp[cdb]->put(dbp[cdb], /* db */
596 MYTID, /* transaction ID */
601 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n", cdb,
607 free(compressed_data);
612 bailIfCursor(MYCURSORS,
613 "attempt to write during r/o cursor");
618 if ((ret = dbp[cdb]->put(dbp[cdb], /* db */
619 tid, /* transaction ID */
623 if (ret == DB_LOCK_DEADLOCK) {
627 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n",
628 cdb, db_strerror(ret));
635 free(compressed_data);
644 * Delete a piece of data. Returns 0 if the operation was successful.
646 int cdb_delete(int cdb, void *key, int keylen)
653 memset(&dkey, 0, sizeof dkey);
658 ret = dbp[cdb]->del(dbp[cdb], MYTID, &dkey, 0);
660 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n", cdb,
662 if (ret != DB_NOTFOUND)
666 bailIfCursor(MYCURSORS,
667 "attempt to delete during r/o cursor");
672 if ((ret = dbp[cdb]->del(dbp[cdb], tid, &dkey, 0))
673 && ret != DB_NOTFOUND) {
674 if (ret == DB_LOCK_DEADLOCK) {
678 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n",
679 cdb, db_strerror(ret));
689 static DBC *localcursor(int cdb)
694 if (MYCURSORS[cdb] == NULL)
695 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &curs, 0);
698 MYCURSORS[cdb]->c_dup(MYCURSORS[cdb], &curs,
702 lprintf(CTDL_EMERG, "localcursor: %s\n", db_strerror(ret));
711 * Fetch a piece of data. If not found, returns NULL. Otherwise, it returns
712 * a struct cdbdata which it is the caller's responsibility to free later on
713 * using the cdb_free() routine.
715 struct cdbdata *cdb_fetch(int cdb, void *key, int keylen)
718 struct cdbdata *tempcdb;
722 memset(&dkey, 0, sizeof(DBT));
727 memset(&dret, 0, sizeof(DBT));
728 dret.flags = DB_DBT_MALLOC;
729 ret = dbp[cdb]->get(dbp[cdb], MYTID, &dkey, &dret, 0);
734 memset(&dret, 0, sizeof(DBT));
735 dret.flags = DB_DBT_MALLOC;
737 curs = localcursor(cdb);
739 ret = curs->c_get(curs, &dkey, &dret, DB_SET);
742 while (ret == DB_LOCK_DEADLOCK);
746 if ((ret != 0) && (ret != DB_NOTFOUND)) {
747 lprintf(CTDL_EMERG, "cdb_fetch(%d): %s\n", cdb,
754 tempcdb = (struct cdbdata *) malloc(sizeof(struct cdbdata));
756 if (tempcdb == NULL) {
758 "cdb_fetch: Cannot allocate memory for tempcdb\n");
762 tempcdb->len = dret.size;
763 tempcdb->ptr = dret.data;
765 cdb_decompress_if_necessary(tempcdb);
772 * Free a cdbdata item.
774 * Note that we only free the 'ptr' portion if it is not NULL. This allows
775 * other code to assume ownership of that memory simply by storing the
776 * pointer elsewhere and then setting 'ptr' to NULL. cdb_free() will then
779 void cdb_free(struct cdbdata *cdb)
787 void cdb_close_cursor(int cdb)
789 if (MYCURSORS[cdb] != NULL)
790 cclose(MYCURSORS[cdb]);
792 MYCURSORS[cdb] = NULL;
796 * Prepare for a sequential search of an entire database.
797 * (There is guaranteed to be no more than one traversal in
798 * progress per thread at any given time.)
800 void cdb_rewind(int cdb)
804 if (MYCURSORS[cdb] != NULL) {
806 "cdb_rewind: must close cursor on database %d before reopening.\n",
809 /* cclose(MYCURSORS[cdb]); */
813 * Now initialize the cursor
815 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &MYCURSORS[cdb], 0);
817 lprintf(CTDL_EMERG, "cdb_rewind: db_cursor: %s\n",
825 * Fetch the next item in a sequential search. Returns a pointer to a
826 * cdbdata structure, or NULL if we've hit the end.
828 struct cdbdata *cdb_next_item(int cdb)
831 struct cdbdata *cdbret;
834 /* Initialize the key/data pair so the flags aren't set. */
835 memset(&key, 0, sizeof(key));
836 memset(&data, 0, sizeof(data));
837 data.flags = DB_DBT_MALLOC;
839 ret = MYCURSORS[cdb]->c_get(MYCURSORS[cdb], &key, &data, DB_NEXT);
842 if (ret != DB_NOTFOUND) {
843 lprintf(CTDL_EMERG, "cdb_next_item(%d): %s\n",
844 cdb, db_strerror(ret));
847 cclose(MYCURSORS[cdb]);
848 MYCURSORS[cdb] = NULL;
849 return NULL; /* presumably, end of file */
852 cdbret = (struct cdbdata *) malloc(sizeof(struct cdbdata));
853 cdbret->len = data.size;
854 cdbret->ptr = data.data;
856 cdb_decompress_if_necessary(cdbret);
865 * Transaction-based stuff. I'm writing this as I bake cookies...
868 void cdb_begin_transaction(void)
871 bailIfCursor(MYCURSORS,
872 "can't begin transaction during r/o cursor");
876 "cdb_begin_transaction: ERROR: nested transaction\n");
883 void cdb_end_transaction(void)
887 for (i = 0; i < MAXCDB; i++)
888 if (MYCURSORS[i] != NULL) {
889 lprintf(CTDL_WARNING,
890 "cdb_end_transaction: WARNING: cursor %d still open at transaction end\n",
892 cclose(MYCURSORS[i]);
898 "cdb_end_transaction: ERROR: txcommit(NULL) !!\n");
907 * Truncate (delete every record)
909 void cdb_trunc(int cdb)
917 "cdb_trunc must not be called in a transaction.\n");
920 bailIfCursor(MYCURSORS,
921 "attempt to write during r/o cursor");
926 if ((ret = dbp[cdb]->truncate(dbp[cdb], /* db */
927 NULL, /* transaction ID */
928 &count, /* #rows deleted */
930 if (ret == DB_LOCK_DEADLOCK) {
935 "cdb_truncate(%d): %s\n", cdb,