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 /*****************************************************************************/
32 #include <sys/types.h>
38 #elif defined(HAVE_DB4_DB_H)
41 #error Neither <db.h> nor <db4/db.h> was found by configure. Install db4-devel.
45 #if DB_VERSION_MAJOR < 4 || DB_VERSION_MINOR < 1
46 #error Citadel requires Berkeley DB v4.1 or newer. Please upgrade.
53 #include "serv_extensions.h"
54 #include "citserver.h"
57 #include "sysdep_decls.h"
60 static DB *dbp[MAXCDB]; /* One DB handle for each Citadel database */
61 static DB_ENV *dbenv; /* The DB environment (global) */
63 struct cdbtsd { /* Thread-specific DB stuff */
64 DB_TXN *tid; /* Transaction handle */
65 DBC *cursors[MAXCDB]; /* Cursors, for traversals... */
72 static pthread_key_t tsdkey;
74 #define MYCURSORS (((struct cdbtsd*)pthread_getspecific(tsdkey))->cursors)
75 #define MYTID (((struct cdbtsd*)pthread_getspecific(tsdkey))->tid)
77 /* just a little helper function */
78 static void txabort(DB_TXN * tid)
82 ret = tid->abort(tid);
85 lprintf(CTDL_EMERG, "cdb_*: txn_abort: %s\n",
91 /* this one is even more helpful than the last. */
92 static void txcommit(DB_TXN * tid)
96 ret = tid->commit(tid, 0);
99 lprintf(CTDL_EMERG, "cdb_*: txn_commit: %s\n",
105 /* are you sensing a pattern yet? */
106 static void txbegin(DB_TXN ** tid)
110 ret = dbenv->txn_begin(dbenv, NULL, tid, 0);
113 lprintf(CTDL_EMERG, "cdb_*: txn_begin: %s\n",
119 static void dbpanic(DB_ENV * env, int errval)
121 lprintf(CTDL_EMERG, "cdb_*: Berkeley DB panic: %d\n", errval);
124 static void cclose(DBC * cursor)
128 if ((ret = cursor->c_close(cursor))) {
129 lprintf(CTDL_EMERG, "cdb_*: c_close: %s\n",
135 static void bailIfCursor(DBC ** cursors, const char *msg)
139 for (i = 0; i < MAXCDB; i++)
140 if (cursors[i] != NULL) {
142 "cdb_*: cursor still in progress on cdb %d: %s\n",
148 static void check_handles(void *arg)
151 struct cdbtsd *tsd = (struct cdbtsd *) arg;
153 bailIfCursor(tsd->cursors, "in check_handles");
155 if (tsd->tid != NULL) {
157 "cdb_*: transaction still in progress!");
163 static void dest_tsd(void *arg)
172 * Ensure that we have a key for thread-specific data. We don't
173 * put anything in here that Citadel cares about; this is just database
174 * related stuff like cursors and transactions.
176 * This should be called immediately after startup by any thread which wants
177 * to use database calls, except for whatever thread calls open_databases.
179 void cdb_allocate_tsd(void)
183 if (pthread_getspecific(tsdkey) != NULL)
186 tsd = malloc(sizeof(struct cdbtsd));
190 memset(tsd->cursors, 0, sizeof tsd->cursors);
191 pthread_setspecific(tsdkey, tsd);
194 void cdb_free_tsd(void)
196 dest_tsd(pthread_getspecific(tsdkey));
197 pthread_setspecific(tsdkey, NULL);
200 void cdb_check_handles(void)
202 check_handles(pthread_getspecific(tsdkey));
207 * Reclaim unused space in the databases. We need to do each one of
208 * these discretely, rather than in a loop.
210 * This is a stub function in the Sleepycat DB backend, because there is no
211 * such API call available.
213 void defrag_databases(void)
220 * Cull the database logs
222 static void cdb_cull_logs(void)
231 /* Get the list of names. */
232 if ((ret = dbenv->log_archive(dbenv, &list, flags)) != 0) {
233 lprintf(CTDL_ERR, "cdb_cull_logs: %s\n", db_strerror(ret));
237 /* Print the list of names. */
239 for (file = list; *file != NULL; ++file) {
240 lprintf(CTDL_DEBUG, "Deleting log: %s\n", *file);
243 snprintf(errmsg, sizeof(errmsg),
244 " ** ERROR **\n \n \n "
245 "Citadel was unable to delete the "
246 "database log file '%s' because of the "
247 "following error:\n \n %s\n \n"
248 " This log file is no longer in use "
249 "and may be safely deleted.\n",
250 *file, strerror(errno));
251 aide_message(errmsg);
259 * Manually initiate log file cull.
261 void cmd_cull(char *argbuf) {
262 if (CtdlAccessCheck(ac_internal)) return;
264 cprintf("%d Database log file cull completed.\n", CIT_OK);
269 * Request a checkpoint of the database.
271 static void cdb_checkpoint(void)
274 static time_t last_run = 0L;
276 /* Only do a checkpoint once per minute. */
277 if ((time(NULL) - last_run) < 60L) {
280 last_run = time(NULL);
282 lprintf(CTDL_DEBUG, "-- db checkpoint --\n");
283 ret = dbenv->txn_checkpoint(dbenv,
284 MAX_CHECKPOINT_KBYTES,
285 MAX_CHECKPOINT_MINUTES, 0);
288 lprintf(CTDL_EMERG, "cdb_checkpoint: txn_checkpoint: %s\n",
293 /* After a successful checkpoint, we can cull the unused logs */
294 if (config.c_auto_cull) {
301 * Main loop for the checkpoint thread.
303 void *checkpoint_thread(void *arg) {
304 struct CitContext checkpointCC;
306 lprintf(CTDL_DEBUG, "checkpoint_thread() initializing\n");
308 memset(&checkpointCC, 0, sizeof(struct CitContext));
309 checkpointCC.internal_pgm = 1;
310 checkpointCC.cs_pid = 0;
311 pthread_setspecific(MyConKey, (void *)&checkpointCC );
315 while (!time_to_die) {
320 lprintf(CTDL_DEBUG, "checkpoint_thread() exiting\n");
325 * Open the various databases we'll be using. Any database which
326 * does not exist should be created. Note that we don't need a
327 * critical section here, because there aren't any active threads
328 * manipulating the database yet.
330 void open_databases(void)
334 char dbfilename[SIZ];
336 char dbdirname[PATH_MAX];
339 char filename[PATH_MAX];
341 #ifndef HAVE_DATA_DIR
342 getcwd(dbdirname, sizeof dbdirname);
343 strcat(dbdirname, "/data");
345 strcat(dbdirname, DATA_DIR"/data");
348 lprintf(CTDL_DEBUG, "cdb_*: open_databases() starting\n");
349 lprintf(CTDL_DEBUG, "Compiled db: %s\n", DB_VERSION_STRING);
350 lprintf(CTDL_INFO, " Linked db: %s\n",
351 db_version(NULL, NULL, NULL));
353 lprintf(CTDL_INFO, "Linked zlib: %s\n", zlibVersion());
357 * Silently try to create the database subdirectory. If it's
358 * already there, no problem.
360 mkdir(dbdirname, 0700);
361 chmod(dbdirname, 0700);
362 chown(dbdirname, CTDLUID, (-1));
364 lprintf(CTDL_DEBUG, "cdb_*: Setting up DB environment\n");
365 db_env_set_func_yield(sched_yield);
366 ret = db_env_create(&dbenv, 0);
368 lprintf(CTDL_EMERG, "cdb_*: db_env_create: %s\n",
372 dbenv->set_errpfx(dbenv, "citserver");
373 dbenv->set_paniccall(dbenv, dbpanic);
376 * We want to specify the shared memory buffer pool cachesize,
377 * but everything else is the default.
379 ret = dbenv->set_cachesize(dbenv, 0, 64 * 1024, 0);
381 lprintf(CTDL_EMERG, "cdb_*: set_cachesize: %s\n",
383 dbenv->close(dbenv, 0);
387 if ((ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT))) {
388 lprintf(CTDL_EMERG, "cdb_*: set_lk_detect: %s\n",
390 dbenv->close(dbenv, 0);
395 DB_CREATE | DB_RECOVER | DB_INIT_MPOOL | DB_PRIVATE |
396 DB_INIT_TXN | DB_INIT_LOCK | DB_THREAD;
397 lprintf(CTDL_DEBUG, "dbenv->open(dbenv, %s, %d, 0)\n", dbdirname,
399 ret = dbenv->open(dbenv, dbdirname, flags, 0);
401 lprintf(CTDL_DEBUG, "cdb_*: dbenv->open: %s\n",
403 dbenv->close(dbenv, 0);
407 lprintf(CTDL_INFO, "cdb_*: Starting up DB\n");
409 for (i = 0; i < MAXCDB; ++i) {
411 /* Create a database handle */
412 ret = db_create(&dbp[i], dbenv, 0);
414 lprintf(CTDL_DEBUG, "cdb_*: db_create: %s\n",
420 /* Arbitrary names for our tables -- we reference them by
421 * number, so we don't have string names for them.
423 snprintf(dbfilename, sizeof dbfilename, "cdb.%02x", i);
425 ret = dbp[i]->open(dbp[i],
430 DB_CREATE | DB_AUTO_COMMIT | DB_THREAD,
433 lprintf(CTDL_EMERG, "cdb_*: db_open[%d]: %s\n", i,
439 if ((ret = pthread_key_create(&tsdkey, dest_tsd))) {
440 lprintf(CTDL_EMERG, "cdb_*: pthread_key_create: %s\n",
447 /* Now make sure we own all the files, because in a few milliseconds
448 * we're going to drop root privs.
450 dp = opendir(dbdirname);
452 while (d = readdir(dp), d != NULL) {
453 if (d->d_name[0] != '.') {
454 snprintf(filename, sizeof filename,
455 "%s/%s", dbdirname, d->d_name);
456 chmod(filename, 0600);
457 chown(filename, CTDLUID, (-1));
463 lprintf(CTDL_DEBUG, "cdb_*: open_databases() finished\n");
465 CtdlRegisterProtoHook(cmd_cull, "CULL", "Cull database logs");
470 * Close all of the db database files we've opened. This can be done
471 * in a loop, since it's just a bunch of closes.
473 void close_databases(void)
480 if ((ret = dbenv->txn_checkpoint(dbenv, 0, 0, 0))) {
482 "cdb_*: txn_checkpoint: %s\n", db_strerror(ret));
485 for (a = 0; a < MAXCDB; ++a) {
486 lprintf(CTDL_INFO, "cdb_*: Closing database %d\n", a);
487 ret = dbp[a]->close(dbp[a], 0);
490 "cdb_*: db_close: %s\n", db_strerror(ret));
495 /* Close the handle. */
496 ret = dbenv->close(dbenv, 0);
499 "cdb_*: DBENV->close: %s\n", db_strerror(ret));
505 * Compression functions only used if we have zlib
509 void cdb_decompress_if_necessary(struct cdbdata *cdb)
511 static int magic = COMPRESS_MAGIC;
512 struct CtdlCompressHeader zheader;
513 char *uncompressed_data;
514 char *compressed_data;
515 uLongf destLen, sourceLen;
519 if (cdb->ptr == NULL)
521 if (memcmp(cdb->ptr, &magic, sizeof(magic)))
524 /* At this point we know we're looking at a compressed item. */
525 memcpy(&zheader, cdb->ptr, sizeof(struct CtdlCompressHeader));
527 compressed_data = cdb->ptr;
528 compressed_data += sizeof(struct CtdlCompressHeader);
530 sourceLen = (uLongf) zheader.compressed_len;
531 destLen = (uLongf) zheader.uncompressed_len;
532 uncompressed_data = malloc(zheader.uncompressed_len);
534 if (uncompress((Bytef *) uncompressed_data,
535 (uLongf *) & destLen,
536 (const Bytef *) compressed_data,
537 (uLong) sourceLen) != Z_OK) {
538 lprintf(CTDL_EMERG, "uncompress() error\n");
543 cdb->len = (size_t) destLen;
544 cdb->ptr = uncompressed_data;
547 #endif /* HAVE_ZLIB */
551 * Store a piece of data. Returns 0 if the operation was successful. If a
552 * key already exists it should be overwritten.
554 int cdb_store(int cdb, void *ckey, int ckeylen, void *cdata, int cdatalen)
562 struct CtdlCompressHeader zheader;
563 char *compressed_data = NULL;
569 memset(&dkey, 0, sizeof(DBT));
570 memset(&ddata, 0, sizeof(DBT));
573 ddata.size = cdatalen;
577 /* Only compress Visit records. Everything else is uncompressed. */
578 if (cdb == CDB_VISIT) {
580 zheader.magic = COMPRESS_MAGIC;
581 zheader.uncompressed_len = cdatalen;
582 buffer_len = ((cdatalen * 101) / 100) + 100
583 + sizeof(struct CtdlCompressHeader);
584 destLen = (uLongf) buffer_len;
585 compressed_data = malloc(buffer_len);
586 if (compress2((Bytef *) (compressed_data +
588 CtdlCompressHeader)),
589 &destLen, (Bytef *) cdata, (uLongf) cdatalen,
591 lprintf(CTDL_EMERG, "compress2() error\n");
594 zheader.compressed_len = (size_t) destLen;
595 memcpy(compressed_data, &zheader,
596 sizeof(struct CtdlCompressHeader));
597 ddata.size = (size_t) (sizeof(struct CtdlCompressHeader) +
598 zheader.compressed_len);
599 ddata.data = compressed_data;
604 ret = dbp[cdb]->put(dbp[cdb], /* db */
605 MYTID, /* transaction ID */
610 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n", cdb,
616 free(compressed_data);
621 bailIfCursor(MYCURSORS,
622 "attempt to write during r/o cursor");
627 if ((ret = dbp[cdb]->put(dbp[cdb], /* db */
628 tid, /* transaction ID */
632 if (ret == DB_LOCK_DEADLOCK) {
636 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n",
637 cdb, db_strerror(ret));
644 free(compressed_data);
653 * Delete a piece of data. Returns 0 if the operation was successful.
655 int cdb_delete(int cdb, void *key, int keylen)
662 memset(&dkey, 0, sizeof dkey);
667 ret = dbp[cdb]->del(dbp[cdb], MYTID, &dkey, 0);
669 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n", cdb,
671 if (ret != DB_NOTFOUND)
675 bailIfCursor(MYCURSORS,
676 "attempt to delete during r/o cursor");
681 if ((ret = dbp[cdb]->del(dbp[cdb], tid, &dkey, 0))
682 && ret != DB_NOTFOUND) {
683 if (ret == DB_LOCK_DEADLOCK) {
687 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n",
688 cdb, db_strerror(ret));
698 static DBC *localcursor(int cdb)
703 if (MYCURSORS[cdb] == NULL)
704 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &curs, 0);
707 MYCURSORS[cdb]->c_dup(MYCURSORS[cdb], &curs,
711 lprintf(CTDL_EMERG, "localcursor: %s\n", db_strerror(ret));
720 * Fetch a piece of data. If not found, returns NULL. Otherwise, it returns
721 * a struct cdbdata which it is the caller's responsibility to free later on
722 * using the cdb_free() routine.
724 struct cdbdata *cdb_fetch(int cdb, void *key, int keylen)
727 struct cdbdata *tempcdb;
731 memset(&dkey, 0, sizeof(DBT));
736 memset(&dret, 0, sizeof(DBT));
737 dret.flags = DB_DBT_MALLOC;
738 ret = dbp[cdb]->get(dbp[cdb], MYTID, &dkey, &dret, 0);
743 memset(&dret, 0, sizeof(DBT));
744 dret.flags = DB_DBT_MALLOC;
746 curs = localcursor(cdb);
748 ret = curs->c_get(curs, &dkey, &dret, DB_SET);
751 while (ret == DB_LOCK_DEADLOCK);
755 if ((ret != 0) && (ret != DB_NOTFOUND)) {
756 lprintf(CTDL_EMERG, "cdb_fetch(%d): %s\n", cdb,
763 tempcdb = (struct cdbdata *) malloc(sizeof(struct cdbdata));
765 if (tempcdb == NULL) {
767 "cdb_fetch: Cannot allocate memory for tempcdb\n");
771 tempcdb->len = dret.size;
772 tempcdb->ptr = dret.data;
774 cdb_decompress_if_necessary(tempcdb);
781 * Free a cdbdata item (ok, this is really no big deal, but we might need to do
782 * more complex stuff with other database managers in the future).
784 void cdb_free(struct cdbdata *cdb)
790 void cdb_close_cursor(int cdb)
792 if (MYCURSORS[cdb] != NULL)
793 cclose(MYCURSORS[cdb]);
795 MYCURSORS[cdb] = NULL;
799 * Prepare for a sequential search of an entire database.
800 * (There is guaranteed to be no more than one traversal in
801 * progress per thread at any given time.)
803 void cdb_rewind(int cdb)
807 if (MYCURSORS[cdb] != NULL) {
809 "cdb_rewind: must close cursor on database %d before reopening.\n",
812 /* cclose(MYCURSORS[cdb]); */
816 * Now initialize the cursor
818 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &MYCURSORS[cdb], 0);
820 lprintf(CTDL_EMERG, "cdb_rewind: db_cursor: %s\n",
828 * Fetch the next item in a sequential search. Returns a pointer to a
829 * cdbdata structure, or NULL if we've hit the end.
831 struct cdbdata *cdb_next_item(int cdb)
834 struct cdbdata *cdbret;
837 /* Initialize the key/data pair so the flags aren't set. */
838 memset(&key, 0, sizeof(key));
839 memset(&data, 0, sizeof(data));
840 data.flags = DB_DBT_MALLOC;
842 ret = MYCURSORS[cdb]->c_get(MYCURSORS[cdb], &key, &data, DB_NEXT);
845 if (ret != DB_NOTFOUND) {
846 lprintf(CTDL_EMERG, "cdb_next_item(%d): %s\n",
847 cdb, db_strerror(ret));
850 cclose(MYCURSORS[cdb]);
851 MYCURSORS[cdb] = NULL;
852 return NULL; /* presumably, end of file */
855 cdbret = (struct cdbdata *) malloc(sizeof(struct cdbdata));
856 cdbret->len = data.size;
857 cdbret->ptr = data.data;
859 cdb_decompress_if_necessary(cdbret);
868 * Transaction-based stuff. I'm writing this as I bake cookies...
871 void cdb_begin_transaction(void)
874 bailIfCursor(MYCURSORS,
875 "can't begin transaction during r/o cursor");
879 "cdb_begin_transaction: ERROR: nested transaction\n");
886 void cdb_end_transaction(void)
890 for (i = 0; i < MAXCDB; i++)
891 if (MYCURSORS[i] != NULL) {
892 lprintf(CTDL_WARNING,
893 "cdb_end_transaction: WARNING: cursor %d still open at transaction end\n",
895 cclose(MYCURSORS[i]);
901 "cdb_end_transaction: ERROR: txcommit(NULL) !!\n");
910 * Truncate (delete every record)
912 void cdb_trunc(int cdb)
920 "cdb_trunc must not be called in a transaction.\n");
923 bailIfCursor(MYCURSORS,
924 "attempt to write during r/o cursor");
929 if ((ret = dbp[cdb]->truncate(dbp[cdb], /* db */
930 NULL, /* transaction ID */
931 &count, /* #rows deleted */
933 if (ret == DB_LOCK_DEADLOCK) {
938 "cdb_truncate(%d): %s\n", cdb,