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];
334 char filename[PATH_MAX];
336 lprintf(CTDL_DEBUG, "cdb_*: open_databases() starting\n");
337 lprintf(CTDL_DEBUG, "Compiled db: %s\n", DB_VERSION_STRING);
338 lprintf(CTDL_INFO, " Linked db: %s\n",
339 db_version(NULL, NULL, NULL));
341 lprintf(CTDL_INFO, "Linked zlib: %s\n", zlibVersion());
345 * Silently try to create the database subdirectory. If it's
346 * already there, no problem.
348 mkdir(ctdl_data_dir, 0700);
349 chmod(ctdl_data_dir, 0700);
350 chown(ctdl_data_dir, CTDLUID, (-1));
352 lprintf(CTDL_DEBUG, "cdb_*: Setting up DB environment\n");
353 db_env_set_func_yield(sched_yield);
354 ret = db_env_create(&dbenv, 0);
356 lprintf(CTDL_EMERG, "cdb_*: db_env_create: %s\n",
360 dbenv->set_errpfx(dbenv, "citserver");
361 dbenv->set_paniccall(dbenv, dbpanic);
364 * We want to specify the shared memory buffer pool cachesize,
365 * but everything else is the default.
367 ret = dbenv->set_cachesize(dbenv, 0, 64 * 1024, 0);
369 lprintf(CTDL_EMERG, "cdb_*: set_cachesize: %s\n",
371 dbenv->close(dbenv, 0);
375 if ((ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT))) {
376 lprintf(CTDL_EMERG, "cdb_*: set_lk_detect: %s\n",
378 dbenv->close(dbenv, 0);
383 DB_CREATE | DB_RECOVER | DB_INIT_MPOOL | DB_PRIVATE |
384 DB_INIT_TXN | DB_INIT_LOCK | DB_THREAD;
385 lprintf(CTDL_DEBUG, "dbenv->open(dbenv, %s, %d, 0)\n", ctdl_data_dir,
387 ret = dbenv->open(dbenv, ctdl_data_dir, flags, 0);
389 lprintf(CTDL_DEBUG, "cdb_*: dbenv->open: %s\n",
391 dbenv->close(dbenv, 0);
395 lprintf(CTDL_INFO, "cdb_*: Starting up DB\n");
397 for (i = 0; i < MAXCDB; ++i) {
399 /* Create a database handle */
400 ret = db_create(&dbp[i], dbenv, 0);
402 lprintf(CTDL_DEBUG, "cdb_*: db_create: %s\n",
408 /* Arbitrary names for our tables -- we reference them by
409 * number, so we don't have string names for them.
411 snprintf(dbfilename, sizeof dbfilename, "cdb.%02x", i);
413 ret = dbp[i]->open(dbp[i],
418 DB_CREATE | DB_AUTO_COMMIT | DB_THREAD,
421 lprintf(CTDL_EMERG, "cdb_*: db_open[%d]: %s\n", i,
427 if ((ret = pthread_key_create(&tsdkey, dest_tsd))) {
428 lprintf(CTDL_EMERG, "cdb_*: pthread_key_create: %s\n",
435 /* Now make sure we own all the files, because in a few milliseconds
436 * we're going to drop root privs.
438 dp = opendir(ctdl_data_dir);
440 while (d = readdir(dp), d != NULL) {
441 if (d->d_name[0] != '.') {
442 snprintf(filename, sizeof filename,
443 "%s/%s", ctdl_data_dir, d->d_name);
444 chmod(filename, 0600);
445 chown(filename, CTDLUID, (-1));
451 lprintf(CTDL_DEBUG, "cdb_*: open_databases() finished\n");
453 CtdlRegisterProtoHook(cmd_cull, "CULL", "Cull database logs");
458 * Close all of the db database files we've opened. This can be done
459 * in a loop, since it's just a bunch of closes.
461 void close_databases(void)
468 if ((ret = dbenv->txn_checkpoint(dbenv, 0, 0, 0))) {
470 "cdb_*: txn_checkpoint: %s\n", db_strerror(ret));
473 for (a = 0; a < MAXCDB; ++a) {
474 lprintf(CTDL_INFO, "cdb_*: Closing database %d\n", a);
475 ret = dbp[a]->close(dbp[a], 0);
478 "cdb_*: db_close: %s\n", db_strerror(ret));
483 /* Close the handle. */
484 ret = dbenv->close(dbenv, 0);
487 "cdb_*: DBENV->close: %s\n", db_strerror(ret));
493 * Compression functions only used if we have zlib
497 void cdb_decompress_if_necessary(struct cdbdata *cdb)
499 static int magic = COMPRESS_MAGIC;
500 struct CtdlCompressHeader zheader;
501 char *uncompressed_data;
502 char *compressed_data;
503 uLongf destLen, sourceLen;
507 if (cdb->ptr == NULL)
509 if (memcmp(cdb->ptr, &magic, sizeof(magic)))
512 /* At this point we know we're looking at a compressed item. */
513 memcpy(&zheader, cdb->ptr, sizeof(struct CtdlCompressHeader));
515 compressed_data = cdb->ptr;
516 compressed_data += sizeof(struct CtdlCompressHeader);
518 sourceLen = (uLongf) zheader.compressed_len;
519 destLen = (uLongf) zheader.uncompressed_len;
520 uncompressed_data = malloc(zheader.uncompressed_len);
522 if (uncompress((Bytef *) uncompressed_data,
523 (uLongf *) & destLen,
524 (const Bytef *) compressed_data,
525 (uLong) sourceLen) != Z_OK) {
526 lprintf(CTDL_EMERG, "uncompress() error\n");
531 cdb->len = (size_t) destLen;
532 cdb->ptr = uncompressed_data;
535 #endif /* HAVE_ZLIB */
539 * Store a piece of data. Returns 0 if the operation was successful. If a
540 * key already exists it should be overwritten.
542 int cdb_store(int cdb, void *ckey, int ckeylen, void *cdata, int cdatalen)
550 struct CtdlCompressHeader zheader;
551 char *compressed_data = NULL;
557 memset(&dkey, 0, sizeof(DBT));
558 memset(&ddata, 0, sizeof(DBT));
561 ddata.size = cdatalen;
565 /* Only compress Visit records. Everything else is uncompressed. */
566 if (cdb == CDB_VISIT) {
568 zheader.magic = COMPRESS_MAGIC;
569 zheader.uncompressed_len = cdatalen;
570 buffer_len = ((cdatalen * 101) / 100) + 100
571 + sizeof(struct CtdlCompressHeader);
572 destLen = (uLongf) buffer_len;
573 compressed_data = malloc(buffer_len);
574 if (compress2((Bytef *) (compressed_data +
576 CtdlCompressHeader)),
577 &destLen, (Bytef *) cdata, (uLongf) cdatalen,
579 lprintf(CTDL_EMERG, "compress2() error\n");
582 zheader.compressed_len = (size_t) destLen;
583 memcpy(compressed_data, &zheader,
584 sizeof(struct CtdlCompressHeader));
585 ddata.size = (size_t) (sizeof(struct CtdlCompressHeader) +
586 zheader.compressed_len);
587 ddata.data = compressed_data;
592 ret = dbp[cdb]->put(dbp[cdb], /* db */
593 MYTID, /* transaction ID */
598 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n", cdb,
604 free(compressed_data);
609 bailIfCursor(MYCURSORS,
610 "attempt to write during r/o cursor");
615 if ((ret = dbp[cdb]->put(dbp[cdb], /* db */
616 tid, /* transaction ID */
620 if (ret == DB_LOCK_DEADLOCK) {
624 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n",
625 cdb, db_strerror(ret));
632 free(compressed_data);
641 * Delete a piece of data. Returns 0 if the operation was successful.
643 int cdb_delete(int cdb, void *key, int keylen)
650 memset(&dkey, 0, sizeof dkey);
655 ret = dbp[cdb]->del(dbp[cdb], MYTID, &dkey, 0);
657 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n", cdb,
659 if (ret != DB_NOTFOUND)
663 bailIfCursor(MYCURSORS,
664 "attempt to delete during r/o cursor");
669 if ((ret = dbp[cdb]->del(dbp[cdb], tid, &dkey, 0))
670 && ret != DB_NOTFOUND) {
671 if (ret == DB_LOCK_DEADLOCK) {
675 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n",
676 cdb, db_strerror(ret));
686 static DBC *localcursor(int cdb)
691 if (MYCURSORS[cdb] == NULL)
692 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &curs, 0);
695 MYCURSORS[cdb]->c_dup(MYCURSORS[cdb], &curs,
699 lprintf(CTDL_EMERG, "localcursor: %s\n", db_strerror(ret));
708 * Fetch a piece of data. If not found, returns NULL. Otherwise, it returns
709 * a struct cdbdata which it is the caller's responsibility to free later on
710 * using the cdb_free() routine.
712 struct cdbdata *cdb_fetch(int cdb, void *key, int keylen)
715 struct cdbdata *tempcdb;
719 memset(&dkey, 0, sizeof(DBT));
724 memset(&dret, 0, sizeof(DBT));
725 dret.flags = DB_DBT_MALLOC;
726 ret = dbp[cdb]->get(dbp[cdb], MYTID, &dkey, &dret, 0);
731 memset(&dret, 0, sizeof(DBT));
732 dret.flags = DB_DBT_MALLOC;
734 curs = localcursor(cdb);
736 ret = curs->c_get(curs, &dkey, &dret, DB_SET);
739 while (ret == DB_LOCK_DEADLOCK);
743 if ((ret != 0) && (ret != DB_NOTFOUND)) {
744 lprintf(CTDL_EMERG, "cdb_fetch(%d): %s\n", cdb,
751 tempcdb = (struct cdbdata *) malloc(sizeof(struct cdbdata));
753 if (tempcdb == NULL) {
755 "cdb_fetch: Cannot allocate memory for tempcdb\n");
759 tempcdb->len = dret.size;
760 tempcdb->ptr = dret.data;
762 cdb_decompress_if_necessary(tempcdb);
769 * Free a cdbdata item.
771 * Note that we only free the 'ptr' portion if it is not NULL. This allows
772 * other code to assume ownership of that memory simply by storing the
773 * pointer elsewhere and then setting 'ptr' to NULL. cdb_free() will then
776 void cdb_free(struct cdbdata *cdb)
784 void cdb_close_cursor(int cdb)
786 if (MYCURSORS[cdb] != NULL)
787 cclose(MYCURSORS[cdb]);
789 MYCURSORS[cdb] = NULL;
793 * Prepare for a sequential search of an entire database.
794 * (There is guaranteed to be no more than one traversal in
795 * progress per thread at any given time.)
797 void cdb_rewind(int cdb)
801 if (MYCURSORS[cdb] != NULL) {
803 "cdb_rewind: must close cursor on database %d before reopening.\n",
806 /* cclose(MYCURSORS[cdb]); */
810 * Now initialize the cursor
812 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &MYCURSORS[cdb], 0);
814 lprintf(CTDL_EMERG, "cdb_rewind: db_cursor: %s\n",
822 * Fetch the next item in a sequential search. Returns a pointer to a
823 * cdbdata structure, or NULL if we've hit the end.
825 struct cdbdata *cdb_next_item(int cdb)
828 struct cdbdata *cdbret;
831 /* Initialize the key/data pair so the flags aren't set. */
832 memset(&key, 0, sizeof(key));
833 memset(&data, 0, sizeof(data));
834 data.flags = DB_DBT_MALLOC;
836 ret = MYCURSORS[cdb]->c_get(MYCURSORS[cdb], &key, &data, DB_NEXT);
839 if (ret != DB_NOTFOUND) {
840 lprintf(CTDL_EMERG, "cdb_next_item(%d): %s\n",
841 cdb, db_strerror(ret));
844 cclose(MYCURSORS[cdb]);
845 MYCURSORS[cdb] = NULL;
846 return NULL; /* presumably, end of file */
849 cdbret = (struct cdbdata *) malloc(sizeof(struct cdbdata));
850 cdbret->len = data.size;
851 cdbret->ptr = data.data;
853 cdb_decompress_if_necessary(cdbret);
862 * Transaction-based stuff. I'm writing this as I bake cookies...
865 void cdb_begin_transaction(void)
868 bailIfCursor(MYCURSORS,
869 "can't begin transaction during r/o cursor");
873 "cdb_begin_transaction: ERROR: nested transaction\n");
880 void cdb_end_transaction(void)
884 for (i = 0; i < MAXCDB; i++)
885 if (MYCURSORS[i] != NULL) {
886 lprintf(CTDL_WARNING,
887 "cdb_end_transaction: WARNING: cursor %d still open at transaction end\n",
889 cclose(MYCURSORS[i]);
895 "cdb_end_transaction: ERROR: txcommit(NULL) !!\n");
904 * Truncate (delete every record)
906 void cdb_trunc(int cdb)
914 "cdb_trunc must not be called in a transaction.\n");
917 bailIfCursor(MYCURSORS,
918 "attempt to write during r/o cursor");
923 if ((ret = dbp[cdb]->truncate(dbp[cdb], /* db */
924 NULL, /* transaction ID */
925 &count, /* #rows deleted */
927 if (ret == DB_LOCK_DEADLOCK) {
932 "cdb_truncate(%d): %s\n", cdb,