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 #ifndef HAVE_DATA_DIR
338 getcwd(dbdirname, sizeof dbdirname);
339 strcat(dbdirname, "/data");
341 strcat(dbdirname, DATA_DIR"/data");
344 lprintf(CTDL_DEBUG, "cdb_*: open_databases() starting\n");
345 lprintf(CTDL_DEBUG, "Compiled db: %s\n", DB_VERSION_STRING);
346 lprintf(CTDL_INFO, " Linked db: %s\n",
347 db_version(NULL, NULL, NULL));
349 lprintf(CTDL_INFO, "Linked zlib: %s\n", zlibVersion());
353 * Silently try to create the database subdirectory. If it's
354 * already there, no problem.
356 mkdir(dbdirname, 0700);
357 chmod(dbdirname, 0700);
358 chown(dbdirname, CTDLUID, (-1));
360 lprintf(CTDL_DEBUG, "cdb_*: Setting up DB environment\n");
361 db_env_set_func_yield(sched_yield);
362 ret = db_env_create(&dbenv, 0);
364 lprintf(CTDL_EMERG, "cdb_*: db_env_create: %s\n",
368 dbenv->set_errpfx(dbenv, "citserver");
369 dbenv->set_paniccall(dbenv, dbpanic);
372 * We want to specify the shared memory buffer pool cachesize,
373 * but everything else is the default.
375 ret = dbenv->set_cachesize(dbenv, 0, 64 * 1024, 0);
377 lprintf(CTDL_EMERG, "cdb_*: set_cachesize: %s\n",
379 dbenv->close(dbenv, 0);
383 if ((ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT))) {
384 lprintf(CTDL_EMERG, "cdb_*: set_lk_detect: %s\n",
386 dbenv->close(dbenv, 0);
391 DB_CREATE | DB_RECOVER | DB_INIT_MPOOL | DB_PRIVATE |
392 DB_INIT_TXN | DB_INIT_LOCK | DB_THREAD;
393 lprintf(CTDL_DEBUG, "dbenv->open(dbenv, %s, %d, 0)\n", dbdirname,
395 ret = dbenv->open(dbenv, dbdirname, flags, 0);
397 lprintf(CTDL_DEBUG, "cdb_*: dbenv->open: %s\n",
399 dbenv->close(dbenv, 0);
403 lprintf(CTDL_INFO, "cdb_*: Starting up DB\n");
405 for (i = 0; i < MAXCDB; ++i) {
407 /* Create a database handle */
408 ret = db_create(&dbp[i], dbenv, 0);
410 lprintf(CTDL_DEBUG, "cdb_*: db_create: %s\n",
416 /* Arbitrary names for our tables -- we reference them by
417 * number, so we don't have string names for them.
419 snprintf(dbfilename, sizeof dbfilename, "cdb.%02x", i);
421 ret = dbp[i]->open(dbp[i],
426 DB_CREATE | DB_AUTO_COMMIT | DB_THREAD,
429 lprintf(CTDL_EMERG, "cdb_*: db_open[%d]: %s\n", i,
435 if ((ret = pthread_key_create(&tsdkey, dest_tsd))) {
436 lprintf(CTDL_EMERG, "cdb_*: pthread_key_create: %s\n",
443 /* Now make sure we own all the files, because in a few milliseconds
444 * we're going to drop root privs.
446 dp = opendir(dbdirname);
448 while (d = readdir(dp), d != NULL) {
449 if (d->d_name[0] != '.') {
450 snprintf(filename, sizeof filename,
451 "%s/%s", dbdirname, d->d_name);
452 chmod(filename, 0600);
453 chown(filename, CTDLUID, (-1));
459 lprintf(CTDL_DEBUG, "cdb_*: open_databases() finished\n");
461 CtdlRegisterProtoHook(cmd_cull, "CULL", "Cull database logs");
466 * Close all of the db database files we've opened. This can be done
467 * in a loop, since it's just a bunch of closes.
469 void close_databases(void)
476 if ((ret = dbenv->txn_checkpoint(dbenv, 0, 0, 0))) {
478 "cdb_*: txn_checkpoint: %s\n", db_strerror(ret));
481 for (a = 0; a < MAXCDB; ++a) {
482 lprintf(CTDL_INFO, "cdb_*: Closing database %d\n", a);
483 ret = dbp[a]->close(dbp[a], 0);
486 "cdb_*: db_close: %s\n", db_strerror(ret));
491 /* Close the handle. */
492 ret = dbenv->close(dbenv, 0);
495 "cdb_*: DBENV->close: %s\n", db_strerror(ret));
501 * Compression functions only used if we have zlib
505 void cdb_decompress_if_necessary(struct cdbdata *cdb)
507 static int magic = COMPRESS_MAGIC;
508 struct CtdlCompressHeader zheader;
509 char *uncompressed_data;
510 char *compressed_data;
511 uLongf destLen, sourceLen;
515 if (cdb->ptr == NULL)
517 if (memcmp(cdb->ptr, &magic, sizeof(magic)))
520 /* At this point we know we're looking at a compressed item. */
521 memcpy(&zheader, cdb->ptr, sizeof(struct CtdlCompressHeader));
523 compressed_data = cdb->ptr;
524 compressed_data += sizeof(struct CtdlCompressHeader);
526 sourceLen = (uLongf) zheader.compressed_len;
527 destLen = (uLongf) zheader.uncompressed_len;
528 uncompressed_data = malloc(zheader.uncompressed_len);
530 if (uncompress((Bytef *) uncompressed_data,
531 (uLongf *) & destLen,
532 (const Bytef *) compressed_data,
533 (uLong) sourceLen) != Z_OK) {
534 lprintf(CTDL_EMERG, "uncompress() error\n");
539 cdb->len = (size_t) destLen;
540 cdb->ptr = uncompressed_data;
543 #endif /* HAVE_ZLIB */
547 * Store a piece of data. Returns 0 if the operation was successful. If a
548 * key already exists it should be overwritten.
550 int cdb_store(int cdb, void *ckey, int ckeylen, void *cdata, int cdatalen)
558 struct CtdlCompressHeader zheader;
559 char *compressed_data = NULL;
565 memset(&dkey, 0, sizeof(DBT));
566 memset(&ddata, 0, sizeof(DBT));
569 ddata.size = cdatalen;
573 /* Only compress Visit records. Everything else is uncompressed. */
574 if (cdb == CDB_VISIT) {
576 zheader.magic = COMPRESS_MAGIC;
577 zheader.uncompressed_len = cdatalen;
578 buffer_len = ((cdatalen * 101) / 100) + 100
579 + sizeof(struct CtdlCompressHeader);
580 destLen = (uLongf) buffer_len;
581 compressed_data = malloc(buffer_len);
582 if (compress2((Bytef *) (compressed_data +
584 CtdlCompressHeader)),
585 &destLen, (Bytef *) cdata, (uLongf) cdatalen,
587 lprintf(CTDL_EMERG, "compress2() error\n");
590 zheader.compressed_len = (size_t) destLen;
591 memcpy(compressed_data, &zheader,
592 sizeof(struct CtdlCompressHeader));
593 ddata.size = (size_t) (sizeof(struct CtdlCompressHeader) +
594 zheader.compressed_len);
595 ddata.data = compressed_data;
600 ret = dbp[cdb]->put(dbp[cdb], /* db */
601 MYTID, /* transaction ID */
606 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n", cdb,
612 free(compressed_data);
617 bailIfCursor(MYCURSORS,
618 "attempt to write during r/o cursor");
623 if ((ret = dbp[cdb]->put(dbp[cdb], /* db */
624 tid, /* transaction ID */
628 if (ret == DB_LOCK_DEADLOCK) {
632 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n",
633 cdb, db_strerror(ret));
640 free(compressed_data);
649 * Delete a piece of data. Returns 0 if the operation was successful.
651 int cdb_delete(int cdb, void *key, int keylen)
658 memset(&dkey, 0, sizeof dkey);
663 ret = dbp[cdb]->del(dbp[cdb], MYTID, &dkey, 0);
665 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n", cdb,
667 if (ret != DB_NOTFOUND)
671 bailIfCursor(MYCURSORS,
672 "attempt to delete during r/o cursor");
677 if ((ret = dbp[cdb]->del(dbp[cdb], tid, &dkey, 0))
678 && ret != DB_NOTFOUND) {
679 if (ret == DB_LOCK_DEADLOCK) {
683 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n",
684 cdb, db_strerror(ret));
694 static DBC *localcursor(int cdb)
699 if (MYCURSORS[cdb] == NULL)
700 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &curs, 0);
703 MYCURSORS[cdb]->c_dup(MYCURSORS[cdb], &curs,
707 lprintf(CTDL_EMERG, "localcursor: %s\n", db_strerror(ret));
716 * Fetch a piece of data. If not found, returns NULL. Otherwise, it returns
717 * a struct cdbdata which it is the caller's responsibility to free later on
718 * using the cdb_free() routine.
720 struct cdbdata *cdb_fetch(int cdb, void *key, int keylen)
723 struct cdbdata *tempcdb;
727 memset(&dkey, 0, sizeof(DBT));
732 memset(&dret, 0, sizeof(DBT));
733 dret.flags = DB_DBT_MALLOC;
734 ret = dbp[cdb]->get(dbp[cdb], MYTID, &dkey, &dret, 0);
739 memset(&dret, 0, sizeof(DBT));
740 dret.flags = DB_DBT_MALLOC;
742 curs = localcursor(cdb);
744 ret = curs->c_get(curs, &dkey, &dret, DB_SET);
747 while (ret == DB_LOCK_DEADLOCK);
751 if ((ret != 0) && (ret != DB_NOTFOUND)) {
752 lprintf(CTDL_EMERG, "cdb_fetch(%d): %s\n", cdb,
759 tempcdb = (struct cdbdata *) malloc(sizeof(struct cdbdata));
761 if (tempcdb == NULL) {
763 "cdb_fetch: Cannot allocate memory for tempcdb\n");
767 tempcdb->len = dret.size;
768 tempcdb->ptr = dret.data;
770 cdb_decompress_if_necessary(tempcdb);
777 * Free a cdbdata item.
779 * Note that we only free the 'ptr' portion if it is not NULL. This allows
780 * other code to assume ownership of that memory simply by storing the
781 * pointer elsewhere and then setting 'ptr' to NULL. cdb_free() will then
784 void cdb_free(struct cdbdata *cdb)
792 void cdb_close_cursor(int cdb)
794 if (MYCURSORS[cdb] != NULL)
795 cclose(MYCURSORS[cdb]);
797 MYCURSORS[cdb] = NULL;
801 * Prepare for a sequential search of an entire database.
802 * (There is guaranteed to be no more than one traversal in
803 * progress per thread at any given time.)
805 void cdb_rewind(int cdb)
809 if (MYCURSORS[cdb] != NULL) {
811 "cdb_rewind: must close cursor on database %d before reopening.\n",
814 /* cclose(MYCURSORS[cdb]); */
818 * Now initialize the cursor
820 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &MYCURSORS[cdb], 0);
822 lprintf(CTDL_EMERG, "cdb_rewind: db_cursor: %s\n",
830 * Fetch the next item in a sequential search. Returns a pointer to a
831 * cdbdata structure, or NULL if we've hit the end.
833 struct cdbdata *cdb_next_item(int cdb)
836 struct cdbdata *cdbret;
839 /* Initialize the key/data pair so the flags aren't set. */
840 memset(&key, 0, sizeof(key));
841 memset(&data, 0, sizeof(data));
842 data.flags = DB_DBT_MALLOC;
844 ret = MYCURSORS[cdb]->c_get(MYCURSORS[cdb], &key, &data, DB_NEXT);
847 if (ret != DB_NOTFOUND) {
848 lprintf(CTDL_EMERG, "cdb_next_item(%d): %s\n",
849 cdb, db_strerror(ret));
852 cclose(MYCURSORS[cdb]);
853 MYCURSORS[cdb] = NULL;
854 return NULL; /* presumably, end of file */
857 cdbret = (struct cdbdata *) malloc(sizeof(struct cdbdata));
858 cdbret->len = data.size;
859 cdbret->ptr = data.data;
861 cdb_decompress_if_necessary(cdbret);
870 * Transaction-based stuff. I'm writing this as I bake cookies...
873 void cdb_begin_transaction(void)
876 bailIfCursor(MYCURSORS,
877 "can't begin transaction during r/o cursor");
881 "cdb_begin_transaction: ERROR: nested transaction\n");
888 void cdb_end_transaction(void)
892 for (i = 0; i < MAXCDB; i++)
893 if (MYCURSORS[i] != NULL) {
894 lprintf(CTDL_WARNING,
895 "cdb_end_transaction: WARNING: cursor %d still open at transaction end\n",
897 cclose(MYCURSORS[i]);
903 "cdb_end_transaction: ERROR: txcommit(NULL) !!\n");
912 * Truncate (delete every record)
914 void cdb_trunc(int cdb)
922 "cdb_trunc must not be called in a transaction.\n");
925 bailIfCursor(MYCURSORS,
926 "attempt to write during r/o cursor");
931 if ((ret = dbp[cdb]->truncate(dbp[cdb], /* db */
932 NULL, /* transaction ID */
933 &count, /* #rows deleted */
935 if (ret == DB_LOCK_DEADLOCK) {
940 "cdb_truncate(%d): %s\n", cdb,