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 /* Verbose logging callback */
81 void cdb_verbose_err(const DB_ENV *dbenv, const char *errpfx, const char *msg)
83 lprintf(CTDL_ALERT, "BDB: %s\n", msg);
87 /* just a little helper function */
88 static void txabort(DB_TXN * tid)
92 ret = tid->abort(tid);
95 lprintf(CTDL_EMERG, "cdb_*: txn_abort: %s\n",
101 /* this one is even more helpful than the last. */
102 static void txcommit(DB_TXN * tid)
106 ret = tid->commit(tid, 0);
109 lprintf(CTDL_EMERG, "cdb_*: txn_commit: %s\n",
115 /* are you sensing a pattern yet? */
116 static void txbegin(DB_TXN ** tid)
120 ret = dbenv->txn_begin(dbenv, NULL, tid, 0);
123 lprintf(CTDL_EMERG, "cdb_*: txn_begin: %s\n",
129 static void dbpanic(DB_ENV * env, int errval)
131 lprintf(CTDL_EMERG, "cdb_*: Berkeley DB panic: %d\n", errval);
134 static void cclose(DBC * cursor)
138 if ((ret = cursor->c_close(cursor))) {
139 lprintf(CTDL_EMERG, "cdb_*: c_close: %s\n",
145 static void bailIfCursor(DBC ** cursors, const char *msg)
149 for (i = 0; i < MAXCDB; i++)
150 if (cursors[i] != NULL) {
152 "cdb_*: cursor still in progress on cdb %d: %s\n",
158 static void check_handles(void *arg)
161 struct cdbtsd *tsd = (struct cdbtsd *) arg;
163 bailIfCursor(tsd->cursors, "in check_handles");
165 if (tsd->tid != NULL) {
167 "cdb_*: transaction still in progress!");
173 static void dest_tsd(void *arg)
182 * Ensure that we have a key for thread-specific data. We don't
183 * put anything in here that Citadel cares about; this is just database
184 * related stuff like cursors and transactions.
186 * This should be called immediately after startup by any thread which wants
187 * to use database calls, except for whatever thread calls open_databases.
189 void cdb_allocate_tsd(void)
193 if (pthread_getspecific(tsdkey) != NULL)
196 tsd = malloc(sizeof(struct cdbtsd));
200 memset(tsd->cursors, 0, sizeof tsd->cursors);
201 pthread_setspecific(tsdkey, tsd);
204 void cdb_free_tsd(void)
206 dest_tsd(pthread_getspecific(tsdkey));
207 pthread_setspecific(tsdkey, NULL);
210 void cdb_check_handles(void)
212 check_handles(pthread_getspecific(tsdkey));
217 * Reclaim unused space in the databases. We need to do each one of
218 * these discretely, rather than in a loop.
220 * This is a stub function in the Sleepycat DB backend, because there is no
221 * such API call available.
223 void defrag_databases(void)
230 * Cull the database logs
232 static void cdb_cull_logs(void)
241 /* Get the list of names. */
242 if ((ret = dbenv->log_archive(dbenv, &list, flags)) != 0) {
243 lprintf(CTDL_ERR, "cdb_cull_logs: %s\n", db_strerror(ret));
247 /* Print the list of names. */
249 for (file = list; *file != NULL; ++file) {
250 lprintf(CTDL_DEBUG, "Deleting log: %s\n", *file);
253 snprintf(errmsg, sizeof(errmsg),
254 " ** ERROR **\n \n \n "
255 "Citadel was unable to delete the "
256 "database log file '%s' because of the "
257 "following error:\n \n %s\n \n"
258 " This log file is no longer in use "
259 "and may be safely deleted.\n",
260 *file, strerror(errno));
261 aide_message(errmsg, "Database Warning Message");
269 * Manually initiate log file cull.
271 void cmd_cull(char *argbuf) {
272 if (CtdlAccessCheck(ac_internal)) return;
274 cprintf("%d Database log file cull completed.\n", CIT_OK);
279 * Request a checkpoint of the database.
281 static void cdb_checkpoint(void)
284 static time_t last_run = 0L;
286 /* Only do a checkpoint once per minute. */
287 if ((time(NULL) - last_run) < 60L) {
290 last_run = time(NULL);
292 lprintf(CTDL_DEBUG, "-- db checkpoint --\n");
293 ret = dbenv->txn_checkpoint(dbenv,
294 MAX_CHECKPOINT_KBYTES,
295 MAX_CHECKPOINT_MINUTES, 0);
298 lprintf(CTDL_EMERG, "cdb_checkpoint: txn_checkpoint: %s\n",
303 /* After a successful checkpoint, we can cull the unused logs */
304 if (config.c_auto_cull) {
311 * Main loop for the checkpoint thread.
313 void *checkpoint_thread(void *arg) {
314 struct CitContext checkpointCC;
316 lprintf(CTDL_DEBUG, "checkpoint_thread() initializing\n");
318 memset(&checkpointCC, 0, sizeof(struct CitContext));
319 checkpointCC.internal_pgm = 1;
320 checkpointCC.cs_pid = 0;
321 pthread_setspecific(MyConKey, (void *)&checkpointCC );
325 while (!time_to_die) {
330 lprintf(CTDL_DEBUG, "checkpoint_thread() exiting\n");
335 * Open the various databases we'll be using. Any database which
336 * does not exist should be created. Note that we don't need a
337 * critical section here, because there aren't any active threads
338 * manipulating the database yet.
340 void open_databases(void)
344 char dbfilename[SIZ];
348 char filename[PATH_MAX];
350 lprintf(CTDL_DEBUG, "cdb_*: open_databases() starting\n");
351 lprintf(CTDL_DEBUG, "Compiled db: %s\n", DB_VERSION_STRING);
352 lprintf(CTDL_INFO, " Linked db: %s\n",
353 db_version(NULL, NULL, NULL));
355 lprintf(CTDL_INFO, "Linked zlib: %s\n", zlibVersion());
359 * Silently try to create the database subdirectory. If it's
360 * already there, no problem.
362 mkdir(ctdl_data_dir, 0700);
363 chmod(ctdl_data_dir, 0700);
364 chown(ctdl_data_dir, CTDLUID, (-1));
366 lprintf(CTDL_DEBUG, "cdb_*: Setting up DB environment\n");
367 db_env_set_func_yield(sched_yield);
368 ret = db_env_create(&dbenv, 0);
370 lprintf(CTDL_EMERG, "cdb_*: db_env_create: %s\n",
374 dbenv->set_errpfx(dbenv, "citserver");
375 dbenv->set_paniccall(dbenv, dbpanic);
376 dbenv->set_errcall(dbenv, cdb_verbose_err);
377 dbenv->set_errpfx(dbenv, "ctdl");
378 #if (DB_VERSION_MAJOR == 4) && (DB_VERSION_MINOR >= 3)
379 dbenv->set_msgcall(dbenv, cdb_verbose_log);
381 dbenv->set_verbose(dbenv, DB_VERB_DEADLOCK, 1);
382 dbenv->set_verbose(dbenv, DB_VERB_RECOVERY, 1);
385 * We want to specify the shared memory buffer pool cachesize,
386 * but everything else is the default.
388 ret = dbenv->set_cachesize(dbenv, 0, 64 * 1024, 0);
390 lprintf(CTDL_EMERG, "cdb_*: set_cachesize: %s\n",
392 dbenv->close(dbenv, 0);
396 if ((ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT))) {
397 lprintf(CTDL_EMERG, "cdb_*: set_lk_detect: %s\n",
399 dbenv->close(dbenv, 0);
404 DB_CREATE | DB_RECOVER | DB_INIT_MPOOL |
405 DB_PRIVATE | DB_INIT_TXN | DB_INIT_LOCK | DB_THREAD;
406 lprintf(CTDL_DEBUG, "dbenv->open(dbenv, %s, %d, 0)\n",
407 ctdl_data_dir, flags);
408 ret = dbenv->open(dbenv, ctdl_data_dir, flags, 0);
410 lprintf(CTDL_DEBUG, "cdb_*: dbenv->open: %s\n",
412 dbenv->close(dbenv, 0);
416 lprintf(CTDL_INFO, "cdb_*: Starting up DB\n");
418 for (i = 0; i < MAXCDB; ++i) {
420 /* Create a database handle */
421 ret = db_create(&dbp[i], dbenv, 0);
423 lprintf(CTDL_DEBUG, "cdb_*: db_create: %s\n",
429 /* Arbitrary names for our tables -- we reference them by
430 * number, so we don't have string names for them.
432 snprintf(dbfilename, sizeof dbfilename, "cdb.%02x", i);
434 ret = dbp[i]->open(dbp[i],
439 DB_CREATE | DB_AUTO_COMMIT | DB_THREAD,
442 lprintf(CTDL_EMERG, "cdb_*: db_open[%d]: %s\n", i,
448 if ((ret = pthread_key_create(&tsdkey, dest_tsd))) {
449 lprintf(CTDL_EMERG, "cdb_*: pthread_key_create: %s\n",
456 /* Now make sure we own all the files, because in a few milliseconds
457 * we're going to drop root privs.
459 dp = opendir(ctdl_data_dir);
461 while (d = readdir(dp), d != NULL) {
462 if (d->d_name[0] != '.') {
463 snprintf(filename, sizeof filename,
464 "%s/%s", ctdl_data_dir, d->d_name);
465 chmod(filename, 0600);
466 chown(filename, CTDLUID, (-1));
472 lprintf(CTDL_DEBUG, "cdb_*: open_databases() finished\n");
474 CtdlRegisterProtoHook(cmd_cull, "CULL", "Cull database logs");
479 * Close all of the db database files we've opened. This can be done
480 * in a loop, since it's just a bunch of closes.
482 void close_databases(void)
489 if ((ret = dbenv->txn_checkpoint(dbenv, 0, 0, 0))) {
491 "cdb_*: txn_checkpoint: %s\n", db_strerror(ret));
494 for (a = 0; a < MAXCDB; ++a) {
495 lprintf(CTDL_INFO, "cdb_*: Closing database %d\n", a);
496 ret = dbp[a]->close(dbp[a], 0);
499 "cdb_*: db_close: %s\n", db_strerror(ret));
504 /* Close the handle. */
505 ret = dbenv->close(dbenv, 0);
508 "cdb_*: DBENV->close: %s\n", db_strerror(ret));
514 * Compression functions only used if we have zlib
518 void cdb_decompress_if_necessary(struct cdbdata *cdb)
520 static int magic = COMPRESS_MAGIC;
521 struct CtdlCompressHeader zheader;
522 char *uncompressed_data;
523 char *compressed_data;
524 uLongf destLen, sourceLen;
528 if (cdb->ptr == NULL)
530 if (memcmp(cdb->ptr, &magic, sizeof(magic)))
533 /* At this point we know we're looking at a compressed item. */
534 memcpy(&zheader, cdb->ptr, sizeof(struct CtdlCompressHeader));
536 compressed_data = cdb->ptr;
537 compressed_data += sizeof(struct CtdlCompressHeader);
539 sourceLen = (uLongf) zheader.compressed_len;
540 destLen = (uLongf) zheader.uncompressed_len;
541 uncompressed_data = malloc(zheader.uncompressed_len);
543 if (uncompress((Bytef *) uncompressed_data,
544 (uLongf *) & destLen,
545 (const Bytef *) compressed_data,
546 (uLong) sourceLen) != Z_OK) {
547 lprintf(CTDL_EMERG, "uncompress() error\n");
552 cdb->len = (size_t) destLen;
553 cdb->ptr = uncompressed_data;
556 #endif /* HAVE_ZLIB */
560 * Store a piece of data. Returns 0 if the operation was successful. If a
561 * key already exists it should be overwritten.
563 int cdb_store(int cdb, void *ckey, int ckeylen, void *cdata, int cdatalen)
571 struct CtdlCompressHeader zheader;
572 char *compressed_data = NULL;
574 size_t buffer_len = 0;
578 memset(&dkey, 0, sizeof(DBT));
579 memset(&ddata, 0, sizeof(DBT));
582 ddata.size = cdatalen;
586 /* Only compress Visit records. Everything else is uncompressed. */
587 if (cdb == CDB_VISIT) {
589 zheader.magic = COMPRESS_MAGIC;
590 zheader.uncompressed_len = cdatalen;
591 buffer_len = ((cdatalen * 101) / 100) + 100
592 + sizeof(struct CtdlCompressHeader);
593 destLen = (uLongf) buffer_len;
594 compressed_data = malloc(buffer_len);
595 if (compress2((Bytef *) (compressed_data +
597 CtdlCompressHeader)),
598 &destLen, (Bytef *) cdata, (uLongf) cdatalen,
600 lprintf(CTDL_EMERG, "compress2() error\n");
603 zheader.compressed_len = (size_t) destLen;
604 memcpy(compressed_data, &zheader,
605 sizeof(struct CtdlCompressHeader));
606 ddata.size = (size_t) (sizeof(struct CtdlCompressHeader) +
607 zheader.compressed_len);
608 ddata.data = compressed_data;
613 ret = dbp[cdb]->put(dbp[cdb], /* db */
614 MYTID, /* transaction ID */
619 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n", cdb,
625 free(compressed_data);
630 bailIfCursor(MYCURSORS,
631 "attempt to write during r/o cursor");
636 if ((ret = dbp[cdb]->put(dbp[cdb], /* db */
637 tid, /* transaction ID */
641 if (ret == DB_LOCK_DEADLOCK) {
645 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n",
646 cdb, db_strerror(ret));
653 free(compressed_data);
662 * Delete a piece of data. Returns 0 if the operation was successful.
664 int cdb_delete(int cdb, void *key, int keylen)
671 memset(&dkey, 0, sizeof dkey);
676 ret = dbp[cdb]->del(dbp[cdb], MYTID, &dkey, 0);
678 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n", cdb,
680 if (ret != DB_NOTFOUND)
684 bailIfCursor(MYCURSORS,
685 "attempt to delete during r/o cursor");
690 if ((ret = dbp[cdb]->del(dbp[cdb], tid, &dkey, 0))
691 && ret != DB_NOTFOUND) {
692 if (ret == DB_LOCK_DEADLOCK) {
696 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n",
697 cdb, db_strerror(ret));
707 static DBC *localcursor(int cdb)
712 if (MYCURSORS[cdb] == NULL)
713 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &curs, 0);
716 MYCURSORS[cdb]->c_dup(MYCURSORS[cdb], &curs,
720 lprintf(CTDL_EMERG, "localcursor: %s\n", db_strerror(ret));
729 * Fetch a piece of data. If not found, returns NULL. Otherwise, it returns
730 * a struct cdbdata which it is the caller's responsibility to free later on
731 * using the cdb_free() routine.
733 struct cdbdata *cdb_fetch(int cdb, void *key, int keylen)
736 struct cdbdata *tempcdb;
740 memset(&dkey, 0, sizeof(DBT));
745 memset(&dret, 0, sizeof(DBT));
746 dret.flags = DB_DBT_MALLOC;
747 ret = dbp[cdb]->get(dbp[cdb], MYTID, &dkey, &dret, 0);
752 memset(&dret, 0, sizeof(DBT));
753 dret.flags = DB_DBT_MALLOC;
755 curs = localcursor(cdb);
757 ret = curs->c_get(curs, &dkey, &dret, DB_SET);
760 while (ret == DB_LOCK_DEADLOCK);
764 if ((ret != 0) && (ret != DB_NOTFOUND)) {
765 lprintf(CTDL_EMERG, "cdb_fetch(%d): %s\n", cdb,
772 tempcdb = (struct cdbdata *) malloc(sizeof(struct cdbdata));
774 if (tempcdb == NULL) {
776 "cdb_fetch: Cannot allocate memory for tempcdb\n");
780 tempcdb->len = dret.size;
781 tempcdb->ptr = dret.data;
783 cdb_decompress_if_necessary(tempcdb);
790 * Free a cdbdata item.
792 * Note that we only free the 'ptr' portion if it is not NULL. This allows
793 * other code to assume ownership of that memory simply by storing the
794 * pointer elsewhere and then setting 'ptr' to NULL. cdb_free() will then
797 void cdb_free(struct cdbdata *cdb)
805 void cdb_close_cursor(int cdb)
807 if (MYCURSORS[cdb] != NULL)
808 cclose(MYCURSORS[cdb]);
810 MYCURSORS[cdb] = NULL;
814 * Prepare for a sequential search of an entire database.
815 * (There is guaranteed to be no more than one traversal in
816 * progress per thread at any given time.)
818 void cdb_rewind(int cdb)
822 if (MYCURSORS[cdb] != NULL) {
824 "cdb_rewind: must close cursor on database %d before reopening.\n",
827 /* cclose(MYCURSORS[cdb]); */
831 * Now initialize the cursor
833 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &MYCURSORS[cdb], 0);
835 lprintf(CTDL_EMERG, "cdb_rewind: db_cursor: %s\n",
843 * Fetch the next item in a sequential search. Returns a pointer to a
844 * cdbdata structure, or NULL if we've hit the end.
846 struct cdbdata *cdb_next_item(int cdb)
849 struct cdbdata *cdbret;
852 /* Initialize the key/data pair so the flags aren't set. */
853 memset(&key, 0, sizeof(key));
854 memset(&data, 0, sizeof(data));
855 data.flags = DB_DBT_MALLOC;
857 ret = MYCURSORS[cdb]->c_get(MYCURSORS[cdb], &key, &data, DB_NEXT);
860 if (ret != DB_NOTFOUND) {
861 lprintf(CTDL_EMERG, "cdb_next_item(%d): %s\n",
862 cdb, db_strerror(ret));
865 cclose(MYCURSORS[cdb]);
866 MYCURSORS[cdb] = NULL;
867 return NULL; /* presumably, end of file */
870 cdbret = (struct cdbdata *) malloc(sizeof(struct cdbdata));
871 cdbret->len = data.size;
872 cdbret->ptr = data.data;
874 cdb_decompress_if_necessary(cdbret);
883 * Transaction-based stuff. I'm writing this as I bake cookies...
886 void cdb_begin_transaction(void)
889 bailIfCursor(MYCURSORS,
890 "can't begin transaction during r/o cursor");
894 "cdb_begin_transaction: ERROR: nested transaction\n");
901 void cdb_end_transaction(void)
905 for (i = 0; i < MAXCDB; i++)
906 if (MYCURSORS[i] != NULL) {
907 lprintf(CTDL_WARNING,
908 "cdb_end_transaction: WARNING: cursor %d still open at transaction end\n",
910 cclose(MYCURSORS[i]);
916 "cdb_end_transaction: ERROR: txcommit(NULL) !!\n");
925 * Truncate (delete every record)
927 void cdb_trunc(int cdb)
935 "cdb_trunc must not be called in a transaction.\n");
938 bailIfCursor(MYCURSORS,
939 "attempt to write during r/o cursor");
944 if ((ret = dbp[cdb]->truncate(dbp[cdb], /* db */
945 NULL, /* transaction ID */
946 &count, /* #rows deleted */
948 if (ret == DB_LOCK_DEADLOCK) {
953 "cdb_truncate(%d): %s\n", cdb,