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 /* Verbose logging callback */
74 void cdb_verbose_log(const DB_ENV *dbenv, const char *msg)
76 lprintf(CTDL_DEBUG, "BDB: %s\n", msg);
80 /* just a little helper function */
81 static void txabort(DB_TXN * tid)
85 ret = tid->abort(tid);
88 lprintf(CTDL_EMERG, "cdb_*: txn_abort: %s\n",
94 /* this one is even more helpful than the last. */
95 static void txcommit(DB_TXN * tid)
99 ret = tid->commit(tid, 0);
102 lprintf(CTDL_EMERG, "cdb_*: txn_commit: %s\n",
108 /* are you sensing a pattern yet? */
109 static void txbegin(DB_TXN ** tid)
113 ret = dbenv->txn_begin(dbenv, NULL, tid, 0);
116 lprintf(CTDL_EMERG, "cdb_*: txn_begin: %s\n",
122 static void dbpanic(DB_ENV * env, int errval)
124 lprintf(CTDL_EMERG, "cdb_*: Berkeley DB panic: %d\n", errval);
127 static void cclose(DBC * cursor)
131 if ((ret = cursor->c_close(cursor))) {
132 lprintf(CTDL_EMERG, "cdb_*: c_close: %s\n",
138 static void bailIfCursor(DBC ** cursors, const char *msg)
142 for (i = 0; i < MAXCDB; i++)
143 if (cursors[i] != NULL) {
145 "cdb_*: cursor still in progress on cdb %d: %s\n",
151 static void check_handles(void *arg)
154 struct cdbtsd *tsd = (struct cdbtsd *) arg;
156 bailIfCursor(tsd->cursors, "in check_handles");
158 if (tsd->tid != NULL) {
160 "cdb_*: transaction still in progress!");
166 static void dest_tsd(void *arg)
175 * Ensure that we have a key for thread-specific data. We don't
176 * put anything in here that Citadel cares about; this is just database
177 * related stuff like cursors and transactions.
179 * This should be called immediately after startup by any thread which wants
180 * to use database calls, except for whatever thread calls open_databases.
182 void cdb_allocate_tsd(void)
186 if (pthread_getspecific(tsdkey) != NULL)
189 tsd = malloc(sizeof(struct cdbtsd));
193 memset(tsd->cursors, 0, sizeof tsd->cursors);
194 pthread_setspecific(tsdkey, tsd);
197 void cdb_free_tsd(void)
199 dest_tsd(pthread_getspecific(tsdkey));
200 pthread_setspecific(tsdkey, NULL);
203 void cdb_check_handles(void)
205 check_handles(pthread_getspecific(tsdkey));
210 * Reclaim unused space in the databases. We need to do each one of
211 * these discretely, rather than in a loop.
213 * This is a stub function in the Sleepycat DB backend, because there is no
214 * such API call available.
216 void defrag_databases(void)
223 * Cull the database logs
225 static void cdb_cull_logs(void)
234 /* Get the list of names. */
235 if ((ret = dbenv->log_archive(dbenv, &list, flags)) != 0) {
236 lprintf(CTDL_ERR, "cdb_cull_logs: %s\n", db_strerror(ret));
240 /* Print the list of names. */
242 for (file = list; *file != NULL; ++file) {
243 lprintf(CTDL_DEBUG, "Deleting log: %s\n", *file);
246 snprintf(errmsg, sizeof(errmsg),
247 " ** ERROR **\n \n \n "
248 "Citadel was unable to delete the "
249 "database log file '%s' because of the "
250 "following error:\n \n %s\n \n"
251 " This log file is no longer in use "
252 "and may be safely deleted.\n",
253 *file, strerror(errno));
254 aide_message(errmsg, "Database Warning Message");
262 * Manually initiate log file cull.
264 void cmd_cull(char *argbuf) {
265 if (CtdlAccessCheck(ac_internal)) return;
267 cprintf("%d Database log file cull completed.\n", CIT_OK);
272 * Request a checkpoint of the database.
274 static void cdb_checkpoint(void)
277 static time_t last_run = 0L;
279 /* Only do a checkpoint once per minute. */
280 if ((time(NULL) - last_run) < 60L) {
283 last_run = time(NULL);
285 lprintf(CTDL_DEBUG, "-- db checkpoint --\n");
286 ret = dbenv->txn_checkpoint(dbenv,
287 MAX_CHECKPOINT_KBYTES,
288 MAX_CHECKPOINT_MINUTES, 0);
291 lprintf(CTDL_EMERG, "cdb_checkpoint: txn_checkpoint: %s\n",
296 /* After a successful checkpoint, we can cull the unused logs */
297 if (config.c_auto_cull) {
304 * Main loop for the checkpoint thread.
306 void *checkpoint_thread(void *arg) {
307 struct CitContext checkpointCC;
309 lprintf(CTDL_DEBUG, "checkpoint_thread() initializing\n");
311 memset(&checkpointCC, 0, sizeof(struct CitContext));
312 checkpointCC.internal_pgm = 1;
313 checkpointCC.cs_pid = 0;
314 pthread_setspecific(MyConKey, (void *)&checkpointCC );
318 while (!time_to_die) {
323 lprintf(CTDL_DEBUG, "checkpoint_thread() exiting\n");
328 * Open the various databases we'll be using. Any database which
329 * does not exist should be created. Note that we don't need a
330 * critical section here, because there aren't any active threads
331 * manipulating the database yet.
333 void open_databases(void)
337 char dbfilename[SIZ];
341 char filename[PATH_MAX];
343 lprintf(CTDL_DEBUG, "cdb_*: open_databases() starting\n");
344 lprintf(CTDL_DEBUG, "Compiled db: %s\n", DB_VERSION_STRING);
345 lprintf(CTDL_INFO, " Linked db: %s\n",
346 db_version(NULL, NULL, NULL));
348 lprintf(CTDL_INFO, "Linked zlib: %s\n", zlibVersion());
352 * Silently try to create the database subdirectory. If it's
353 * already there, no problem.
355 mkdir(ctdl_data_dir, 0700);
356 chmod(ctdl_data_dir, 0700);
357 chown(ctdl_data_dir, CTDLUID, (-1));
359 lprintf(CTDL_DEBUG, "cdb_*: Setting up DB environment\n");
360 db_env_set_func_yield(sched_yield);
361 ret = db_env_create(&dbenv, 0);
363 lprintf(CTDL_EMERG, "cdb_*: db_env_create: %s\n",
367 dbenv->set_errpfx(dbenv, "citserver");
368 dbenv->set_paniccall(dbenv, dbpanic);
369 dbenv->set_msgcall(dbenv, cdb_verbose_log);
370 dbenv->set_verbose(dbenv, DB_VERB_DEADLOCK, 1);
371 dbenv->set_verbose(dbenv, DB_VERB_RECOVERY, 1);
374 * We want to specify the shared memory buffer pool cachesize,
375 * but everything else is the default.
377 ret = dbenv->set_cachesize(dbenv, 0, 64 * 1024, 0);
379 lprintf(CTDL_EMERG, "cdb_*: set_cachesize: %s\n",
381 dbenv->close(dbenv, 0);
385 if ((ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT))) {
386 lprintf(CTDL_EMERG, "cdb_*: set_lk_detect: %s\n",
388 dbenv->close(dbenv, 0);
393 DB_CREATE | DB_RECOVER | DB_INIT_MPOOL |
394 DB_PRIVATE | DB_INIT_TXN | DB_INIT_LOCK | DB_THREAD;
395 lprintf(CTDL_DEBUG, "dbenv->open(dbenv, %s, %d, 0)\n",
396 ctdl_data_dir, flags);
397 ret = dbenv->open(dbenv, ctdl_data_dir, flags, 0);
399 lprintf(CTDL_DEBUG, "cdb_*: dbenv->open: %s\n",
401 dbenv->close(dbenv, 0);
405 lprintf(CTDL_INFO, "cdb_*: Starting up DB\n");
407 for (i = 0; i < MAXCDB; ++i) {
409 /* Create a database handle */
410 ret = db_create(&dbp[i], dbenv, 0);
412 lprintf(CTDL_DEBUG, "cdb_*: db_create: %s\n",
418 /* Arbitrary names for our tables -- we reference them by
419 * number, so we don't have string names for them.
421 snprintf(dbfilename, sizeof dbfilename, "cdb.%02x", i);
423 ret = dbp[i]->open(dbp[i],
428 DB_CREATE | DB_AUTO_COMMIT | DB_THREAD,
431 lprintf(CTDL_EMERG, "cdb_*: db_open[%d]: %s\n", i,
437 if ((ret = pthread_key_create(&tsdkey, dest_tsd))) {
438 lprintf(CTDL_EMERG, "cdb_*: pthread_key_create: %s\n",
445 /* Now make sure we own all the files, because in a few milliseconds
446 * we're going to drop root privs.
448 dp = opendir(ctdl_data_dir);
450 while (d = readdir(dp), d != NULL) {
451 if (d->d_name[0] != '.') {
452 snprintf(filename, sizeof filename,
453 "%s/%s", ctdl_data_dir, d->d_name);
454 chmod(filename, 0600);
455 chown(filename, CTDLUID, (-1));
461 lprintf(CTDL_DEBUG, "cdb_*: open_databases() finished\n");
463 CtdlRegisterProtoHook(cmd_cull, "CULL", "Cull database logs");
468 * Close all of the db database files we've opened. This can be done
469 * in a loop, since it's just a bunch of closes.
471 void close_databases(void)
478 if ((ret = dbenv->txn_checkpoint(dbenv, 0, 0, 0))) {
480 "cdb_*: txn_checkpoint: %s\n", db_strerror(ret));
483 for (a = 0; a < MAXCDB; ++a) {
484 lprintf(CTDL_INFO, "cdb_*: Closing database %d\n", a);
485 ret = dbp[a]->close(dbp[a], 0);
488 "cdb_*: db_close: %s\n", db_strerror(ret));
493 /* Close the handle. */
494 ret = dbenv->close(dbenv, 0);
497 "cdb_*: DBENV->close: %s\n", db_strerror(ret));
503 * Compression functions only used if we have zlib
507 void cdb_decompress_if_necessary(struct cdbdata *cdb)
509 static int magic = COMPRESS_MAGIC;
510 struct CtdlCompressHeader zheader;
511 char *uncompressed_data;
512 char *compressed_data;
513 uLongf destLen, sourceLen;
517 if (cdb->ptr == NULL)
519 if (memcmp(cdb->ptr, &magic, sizeof(magic)))
522 /* At this point we know we're looking at a compressed item. */
523 memcpy(&zheader, cdb->ptr, sizeof(struct CtdlCompressHeader));
525 compressed_data = cdb->ptr;
526 compressed_data += sizeof(struct CtdlCompressHeader);
528 sourceLen = (uLongf) zheader.compressed_len;
529 destLen = (uLongf) zheader.uncompressed_len;
530 uncompressed_data = malloc(zheader.uncompressed_len);
532 if (uncompress((Bytef *) uncompressed_data,
533 (uLongf *) & destLen,
534 (const Bytef *) compressed_data,
535 (uLong) sourceLen) != Z_OK) {
536 lprintf(CTDL_EMERG, "uncompress() error\n");
541 cdb->len = (size_t) destLen;
542 cdb->ptr = uncompressed_data;
545 #endif /* HAVE_ZLIB */
549 * Store a piece of data. Returns 0 if the operation was successful. If a
550 * key already exists it should be overwritten.
552 int cdb_store(int cdb, void *ckey, int ckeylen, void *cdata, int cdatalen)
560 struct CtdlCompressHeader zheader;
561 char *compressed_data = NULL;
567 memset(&dkey, 0, sizeof(DBT));
568 memset(&ddata, 0, sizeof(DBT));
571 ddata.size = cdatalen;
575 /* Only compress Visit records. Everything else is uncompressed. */
576 if (cdb == CDB_VISIT) {
578 zheader.magic = COMPRESS_MAGIC;
579 zheader.uncompressed_len = cdatalen;
580 buffer_len = ((cdatalen * 101) / 100) + 100
581 + sizeof(struct CtdlCompressHeader);
582 destLen = (uLongf) buffer_len;
583 compressed_data = malloc(buffer_len);
584 if (compress2((Bytef *) (compressed_data +
586 CtdlCompressHeader)),
587 &destLen, (Bytef *) cdata, (uLongf) cdatalen,
589 lprintf(CTDL_EMERG, "compress2() error\n");
592 zheader.compressed_len = (size_t) destLen;
593 memcpy(compressed_data, &zheader,
594 sizeof(struct CtdlCompressHeader));
595 ddata.size = (size_t) (sizeof(struct CtdlCompressHeader) +
596 zheader.compressed_len);
597 ddata.data = compressed_data;
602 ret = dbp[cdb]->put(dbp[cdb], /* db */
603 MYTID, /* transaction ID */
608 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n", cdb,
614 free(compressed_data);
619 bailIfCursor(MYCURSORS,
620 "attempt to write during r/o cursor");
625 if ((ret = dbp[cdb]->put(dbp[cdb], /* db */
626 tid, /* transaction ID */
630 if (ret == DB_LOCK_DEADLOCK) {
634 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n",
635 cdb, db_strerror(ret));
642 free(compressed_data);
651 * Delete a piece of data. Returns 0 if the operation was successful.
653 int cdb_delete(int cdb, void *key, int keylen)
660 memset(&dkey, 0, sizeof dkey);
665 ret = dbp[cdb]->del(dbp[cdb], MYTID, &dkey, 0);
667 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n", cdb,
669 if (ret != DB_NOTFOUND)
673 bailIfCursor(MYCURSORS,
674 "attempt to delete during r/o cursor");
679 if ((ret = dbp[cdb]->del(dbp[cdb], tid, &dkey, 0))
680 && ret != DB_NOTFOUND) {
681 if (ret == DB_LOCK_DEADLOCK) {
685 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n",
686 cdb, db_strerror(ret));
696 static DBC *localcursor(int cdb)
701 if (MYCURSORS[cdb] == NULL)
702 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &curs, 0);
705 MYCURSORS[cdb]->c_dup(MYCURSORS[cdb], &curs,
709 lprintf(CTDL_EMERG, "localcursor: %s\n", db_strerror(ret));
718 * Fetch a piece of data. If not found, returns NULL. Otherwise, it returns
719 * a struct cdbdata which it is the caller's responsibility to free later on
720 * using the cdb_free() routine.
722 struct cdbdata *cdb_fetch(int cdb, void *key, int keylen)
725 struct cdbdata *tempcdb;
729 memset(&dkey, 0, sizeof(DBT));
734 memset(&dret, 0, sizeof(DBT));
735 dret.flags = DB_DBT_MALLOC;
736 ret = dbp[cdb]->get(dbp[cdb], MYTID, &dkey, &dret, 0);
741 memset(&dret, 0, sizeof(DBT));
742 dret.flags = DB_DBT_MALLOC;
744 curs = localcursor(cdb);
746 ret = curs->c_get(curs, &dkey, &dret, DB_SET);
749 while (ret == DB_LOCK_DEADLOCK);
753 if ((ret != 0) && (ret != DB_NOTFOUND)) {
754 lprintf(CTDL_EMERG, "cdb_fetch(%d): %s\n", cdb,
761 tempcdb = (struct cdbdata *) malloc(sizeof(struct cdbdata));
763 if (tempcdb == NULL) {
765 "cdb_fetch: Cannot allocate memory for tempcdb\n");
769 tempcdb->len = dret.size;
770 tempcdb->ptr = dret.data;
772 cdb_decompress_if_necessary(tempcdb);
779 * Free a cdbdata item.
781 * Note that we only free the 'ptr' portion if it is not NULL. This allows
782 * other code to assume ownership of that memory simply by storing the
783 * pointer elsewhere and then setting 'ptr' to NULL. cdb_free() will then
786 void cdb_free(struct cdbdata *cdb)
794 void cdb_close_cursor(int cdb)
796 if (MYCURSORS[cdb] != NULL)
797 cclose(MYCURSORS[cdb]);
799 MYCURSORS[cdb] = NULL;
803 * Prepare for a sequential search of an entire database.
804 * (There is guaranteed to be no more than one traversal in
805 * progress per thread at any given time.)
807 void cdb_rewind(int cdb)
811 if (MYCURSORS[cdb] != NULL) {
813 "cdb_rewind: must close cursor on database %d before reopening.\n",
816 /* cclose(MYCURSORS[cdb]); */
820 * Now initialize the cursor
822 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &MYCURSORS[cdb], 0);
824 lprintf(CTDL_EMERG, "cdb_rewind: db_cursor: %s\n",
832 * Fetch the next item in a sequential search. Returns a pointer to a
833 * cdbdata structure, or NULL if we've hit the end.
835 struct cdbdata *cdb_next_item(int cdb)
838 struct cdbdata *cdbret;
841 /* Initialize the key/data pair so the flags aren't set. */
842 memset(&key, 0, sizeof(key));
843 memset(&data, 0, sizeof(data));
844 data.flags = DB_DBT_MALLOC;
846 ret = MYCURSORS[cdb]->c_get(MYCURSORS[cdb], &key, &data, DB_NEXT);
849 if (ret != DB_NOTFOUND) {
850 lprintf(CTDL_EMERG, "cdb_next_item(%d): %s\n",
851 cdb, db_strerror(ret));
854 cclose(MYCURSORS[cdb]);
855 MYCURSORS[cdb] = NULL;
856 return NULL; /* presumably, end of file */
859 cdbret = (struct cdbdata *) malloc(sizeof(struct cdbdata));
860 cdbret->len = data.size;
861 cdbret->ptr = data.data;
863 cdb_decompress_if_necessary(cdbret);
872 * Transaction-based stuff. I'm writing this as I bake cookies...
875 void cdb_begin_transaction(void)
878 bailIfCursor(MYCURSORS,
879 "can't begin transaction during r/o cursor");
883 "cdb_begin_transaction: ERROR: nested transaction\n");
890 void cdb_end_transaction(void)
894 for (i = 0; i < MAXCDB; i++)
895 if (MYCURSORS[i] != NULL) {
896 lprintf(CTDL_WARNING,
897 "cdb_end_transaction: WARNING: cursor %d still open at transaction end\n",
899 cclose(MYCURSORS[i]);
905 "cdb_end_transaction: ERROR: txcommit(NULL) !!\n");
914 * Truncate (delete every record)
916 void cdb_trunc(int cdb)
924 "cdb_trunc must not be called in a transaction.\n");
927 bailIfCursor(MYCURSORS,
928 "attempt to write during r/o cursor");
933 if ((ret = dbp[cdb]->truncate(dbp[cdb], /* db */
934 NULL, /* transaction ID */
935 &count, /* #rows deleted */
937 if (ret == DB_LOCK_DEADLOCK) {
942 "cdb_truncate(%d): %s\n", cdb,