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);
260 * Request a checkpoint of the database.
262 static void cdb_checkpoint(void)
265 static time_t last_run = 0L;
267 /* Only do a checkpoint once per minute. */
268 if ((time(NULL) - last_run) < 60L) {
271 last_run = time(NULL);
273 lprintf(CTDL_DEBUG, "-- db checkpoint --\n");
274 ret = dbenv->txn_checkpoint(dbenv,
275 MAX_CHECKPOINT_KBYTES,
276 MAX_CHECKPOINT_MINUTES, 0);
279 lprintf(CTDL_EMERG, "cdb_checkpoint: txn_checkpoint: %s\n",
284 /* After a successful checkpoint, we can cull the unused logs */
290 * Main loop for the checkpoint thread.
292 void *checkpoint_thread(void *arg) {
293 struct CitContext checkpointCC;
295 lprintf(CTDL_DEBUG, "checkpoint_thread() initializing\n");
297 memset(&checkpointCC, 0, sizeof(struct CitContext));
298 checkpointCC.internal_pgm = 1;
299 checkpointCC.cs_pid = 0;
300 pthread_setspecific(MyConKey, (void *)&checkpointCC );
304 while (!time_to_die) {
309 lprintf(CTDL_DEBUG, "checkpoint_thread() exiting\n");
314 * Open the various databases we'll be using. Any database which
315 * does not exist should be created. Note that we don't need a
316 * critical section here, because there aren't any active threads
317 * manipulating the database yet.
319 void open_databases(void)
323 char dbfilename[SIZ];
325 char dbdirname[PATH_MAX];
328 char filename[PATH_MAX];
331 getcwd(dbdirname, sizeof dbdirname);
332 strcat(dbdirname, "/data");
334 lprintf(CTDL_DEBUG, "cdb_*: open_databases() starting\n");
335 lprintf(CTDL_DEBUG, "Compiled db: %s\n", DB_VERSION_STRING);
336 lprintf(CTDL_INFO, " Linked db: %s\n",
337 db_version(NULL, NULL, NULL));
339 lprintf(CTDL_INFO, "Linked zlib: %s\n", zlibVersion());
343 * Silently try to create the database subdirectory. If it's
344 * already there, no problem.
346 mkdir(dbdirname, 0700);
347 chmod(dbdirname, 0700);
348 chown(dbdirname, CTDLUID, (-1));
350 lprintf(CTDL_DEBUG, "cdb_*: Setting up DB environment\n");
351 db_env_set_func_yield(sched_yield);
352 ret = db_env_create(&dbenv, 0);
354 lprintf(CTDL_EMERG, "cdb_*: db_env_create: %s\n",
358 dbenv->set_errpfx(dbenv, "citserver");
359 dbenv->set_paniccall(dbenv, dbpanic);
362 * We want to specify the shared memory buffer pool cachesize,
363 * but everything else is the default.
365 ret = dbenv->set_cachesize(dbenv, 0, 64 * 1024, 0);
367 lprintf(CTDL_EMERG, "cdb_*: set_cachesize: %s\n",
369 dbenv->close(dbenv, 0);
373 if ((ret = dbenv->set_lk_detect(dbenv, DB_LOCK_DEFAULT))) {
374 lprintf(CTDL_EMERG, "cdb_*: set_lk_detect: %s\n",
376 dbenv->close(dbenv, 0);
381 DB_CREATE | DB_RECOVER | DB_INIT_MPOOL | DB_PRIVATE |
382 DB_INIT_TXN | DB_INIT_LOCK | DB_THREAD;
383 lprintf(CTDL_DEBUG, "dbenv->open(dbenv, %s, %d, 0)\n", dbdirname,
385 ret = dbenv->open(dbenv, dbdirname, flags, 0);
387 lprintf(CTDL_DEBUG, "cdb_*: dbenv->open: %s\n",
389 dbenv->close(dbenv, 0);
393 lprintf(CTDL_INFO, "cdb_*: Starting up DB\n");
395 for (i = 0; i < MAXCDB; ++i) {
397 /* Create a database handle */
398 ret = db_create(&dbp[i], dbenv, 0);
400 lprintf(CTDL_DEBUG, "cdb_*: db_create: %s\n",
406 /* Arbitrary names for our tables -- we reference them by
407 * number, so we don't have string names for them.
409 snprintf(dbfilename, sizeof dbfilename, "cdb.%02x", i);
411 ret = dbp[i]->open(dbp[i],
416 DB_CREATE | DB_AUTO_COMMIT | DB_THREAD,
419 lprintf(CTDL_EMERG, "cdb_*: db_open[%d]: %s\n", i,
425 if ((ret = pthread_key_create(&tsdkey, dest_tsd))) {
426 lprintf(CTDL_EMERG, "cdb_*: pthread_key_create: %s\n",
433 /* Now make sure we own all the files, because in a few milliseconds
434 * we're going to drop root privs.
436 dp = opendir(dbdirname);
438 while (d = readdir(dp), d != NULL) {
439 if (d->d_name[0] != '.') {
440 snprintf(filename, sizeof filename,
441 "%s/%s", dbdirname, d->d_name);
442 chmod(filename, 0600);
443 chown(filename, CTDLUID, (-1));
449 lprintf(CTDL_DEBUG, "cdb_*: open_databases() finished\n");
454 * Close all of the db database files we've opened. This can be done
455 * in a loop, since it's just a bunch of closes.
457 void close_databases(void)
464 if ((ret = dbenv->txn_checkpoint(dbenv, 0, 0, 0))) {
466 "cdb_*: txn_checkpoint: %s\n", db_strerror(ret));
469 for (a = 0; a < MAXCDB; ++a) {
470 lprintf(CTDL_INFO, "cdb_*: Closing database %d\n", a);
471 ret = dbp[a]->close(dbp[a], 0);
474 "cdb_*: db_close: %s\n", db_strerror(ret));
479 /* Close the handle. */
480 ret = dbenv->close(dbenv, 0);
483 "cdb_*: DBENV->close: %s\n", db_strerror(ret));
489 * Compression functions only used if we have zlib
493 void cdb_decompress_if_necessary(struct cdbdata *cdb)
495 static int magic = COMPRESS_MAGIC;
496 struct CtdlCompressHeader zheader;
497 char *uncompressed_data;
498 char *compressed_data;
499 uLongf destLen, sourceLen;
503 if (cdb->ptr == NULL)
505 if (memcmp(cdb->ptr, &magic, sizeof(magic)))
508 /* At this point we know we're looking at a compressed item. */
509 memcpy(&zheader, cdb->ptr, sizeof(struct CtdlCompressHeader));
511 compressed_data = cdb->ptr;
512 compressed_data += sizeof(struct CtdlCompressHeader);
514 sourceLen = (uLongf) zheader.compressed_len;
515 destLen = (uLongf) zheader.uncompressed_len;
516 uncompressed_data = malloc(zheader.uncompressed_len);
518 if (uncompress((Bytef *) uncompressed_data,
519 (uLongf *) & destLen,
520 (const Bytef *) compressed_data,
521 (uLong) sourceLen) != Z_OK) {
522 lprintf(CTDL_EMERG, "uncompress() error\n");
527 cdb->len = (size_t) destLen;
528 cdb->ptr = uncompressed_data;
531 #endif /* HAVE_ZLIB */
535 * Store a piece of data. Returns 0 if the operation was successful. If a
536 * key already exists it should be overwritten.
538 int cdb_store(int cdb, void *ckey, int ckeylen, void *cdata, int cdatalen)
546 struct CtdlCompressHeader zheader;
547 char *compressed_data = NULL;
553 memset(&dkey, 0, sizeof(DBT));
554 memset(&ddata, 0, sizeof(DBT));
557 ddata.size = cdatalen;
561 /* Only compress Visit records. Everything else is uncompressed. */
562 if (cdb == CDB_VISIT) {
564 zheader.magic = COMPRESS_MAGIC;
565 zheader.uncompressed_len = cdatalen;
566 buffer_len = ((cdatalen * 101) / 100) + 100
567 + sizeof(struct CtdlCompressHeader);
568 destLen = (uLongf) buffer_len;
569 compressed_data = malloc(buffer_len);
570 if (compress2((Bytef *) (compressed_data +
572 CtdlCompressHeader)),
573 &destLen, (Bytef *) cdata, (uLongf) cdatalen,
575 lprintf(CTDL_EMERG, "compress2() error\n");
578 zheader.compressed_len = (size_t) destLen;
579 memcpy(compressed_data, &zheader,
580 sizeof(struct CtdlCompressHeader));
581 ddata.size = (size_t) (sizeof(struct CtdlCompressHeader) +
582 zheader.compressed_len);
583 ddata.data = compressed_data;
588 ret = dbp[cdb]->put(dbp[cdb], /* db */
589 MYTID, /* transaction ID */
594 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n", cdb,
600 free(compressed_data);
605 bailIfCursor(MYCURSORS,
606 "attempt to write during r/o cursor");
611 if ((ret = dbp[cdb]->put(dbp[cdb], /* db */
612 tid, /* transaction ID */
616 if (ret == DB_LOCK_DEADLOCK) {
620 lprintf(CTDL_EMERG, "cdb_store(%d): %s\n",
621 cdb, db_strerror(ret));
628 free(compressed_data);
637 * Delete a piece of data. Returns 0 if the operation was successful.
639 int cdb_delete(int cdb, void *key, int keylen)
646 memset(&dkey, 0, sizeof dkey);
651 ret = dbp[cdb]->del(dbp[cdb], MYTID, &dkey, 0);
653 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n", cdb,
655 if (ret != DB_NOTFOUND)
659 bailIfCursor(MYCURSORS,
660 "attempt to delete during r/o cursor");
665 if ((ret = dbp[cdb]->del(dbp[cdb], tid, &dkey, 0))
666 && ret != DB_NOTFOUND) {
667 if (ret == DB_LOCK_DEADLOCK) {
671 lprintf(CTDL_EMERG, "cdb_delete(%d): %s\n",
672 cdb, db_strerror(ret));
682 static DBC *localcursor(int cdb)
687 if (MYCURSORS[cdb] == NULL)
688 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &curs, 0);
691 MYCURSORS[cdb]->c_dup(MYCURSORS[cdb], &curs,
695 lprintf(CTDL_EMERG, "localcursor: %s\n", db_strerror(ret));
704 * Fetch a piece of data. If not found, returns NULL. Otherwise, it returns
705 * a struct cdbdata which it is the caller's responsibility to free later on
706 * using the cdb_free() routine.
708 struct cdbdata *cdb_fetch(int cdb, void *key, int keylen)
711 struct cdbdata *tempcdb;
715 memset(&dkey, 0, sizeof(DBT));
720 memset(&dret, 0, sizeof(DBT));
721 dret.flags = DB_DBT_MALLOC;
722 ret = dbp[cdb]->get(dbp[cdb], MYTID, &dkey, &dret, 0);
727 memset(&dret, 0, sizeof(DBT));
728 dret.flags = DB_DBT_MALLOC;
730 curs = localcursor(cdb);
732 ret = curs->c_get(curs, &dkey, &dret, DB_SET);
735 while (ret == DB_LOCK_DEADLOCK);
739 if ((ret != 0) && (ret != DB_NOTFOUND)) {
740 lprintf(CTDL_EMERG, "cdb_fetch(%d): %s\n", cdb,
747 tempcdb = (struct cdbdata *) malloc(sizeof(struct cdbdata));
749 if (tempcdb == NULL) {
751 "cdb_fetch: Cannot allocate memory for tempcdb\n");
755 tempcdb->len = dret.size;
756 tempcdb->ptr = dret.data;
758 cdb_decompress_if_necessary(tempcdb);
765 * Free a cdbdata item (ok, this is really no big deal, but we might need to do
766 * more complex stuff with other database managers in the future).
768 void cdb_free(struct cdbdata *cdb)
774 void cdb_close_cursor(int cdb)
776 if (MYCURSORS[cdb] != NULL)
777 cclose(MYCURSORS[cdb]);
779 MYCURSORS[cdb] = NULL;
783 * Prepare for a sequential search of an entire database.
784 * (There is guaranteed to be no more than one traversal in
785 * progress per thread at any given time.)
787 void cdb_rewind(int cdb)
791 if (MYCURSORS[cdb] != NULL) {
793 "cdb_rewind: must close cursor on database %d before reopening.\n",
796 /* cclose(MYCURSORS[cdb]); */
800 * Now initialize the cursor
802 ret = dbp[cdb]->cursor(dbp[cdb], MYTID, &MYCURSORS[cdb], 0);
804 lprintf(CTDL_EMERG, "cdb_rewind: db_cursor: %s\n",
812 * Fetch the next item in a sequential search. Returns a pointer to a
813 * cdbdata structure, or NULL if we've hit the end.
815 struct cdbdata *cdb_next_item(int cdb)
818 struct cdbdata *cdbret;
821 /* Initialize the key/data pair so the flags aren't set. */
822 memset(&key, 0, sizeof(key));
823 memset(&data, 0, sizeof(data));
824 data.flags = DB_DBT_MALLOC;
826 ret = MYCURSORS[cdb]->c_get(MYCURSORS[cdb], &key, &data, DB_NEXT);
829 if (ret != DB_NOTFOUND) {
830 lprintf(CTDL_EMERG, "cdb_next_item(%d): %s\n",
831 cdb, db_strerror(ret));
834 cclose(MYCURSORS[cdb]);
835 MYCURSORS[cdb] = NULL;
836 return NULL; /* presumably, end of file */
839 cdbret = (struct cdbdata *) malloc(sizeof(struct cdbdata));
840 cdbret->len = data.size;
841 cdbret->ptr = data.data;
843 cdb_decompress_if_necessary(cdbret);
852 * Transaction-based stuff. I'm writing this as I bake cookies...
855 void cdb_begin_transaction(void)
858 bailIfCursor(MYCURSORS,
859 "can't begin transaction during r/o cursor");
863 "cdb_begin_transaction: ERROR: nested transaction\n");
870 void cdb_end_transaction(void)
874 for (i = 0; i < MAXCDB; i++)
875 if (MYCURSORS[i] != NULL) {
876 lprintf(CTDL_WARNING,
877 "cdb_end_transaction: WARNING: cursor %d still open at transaction end\n",
879 cclose(MYCURSORS[i]);
885 "cdb_end_transaction: ERROR: txcommit(NULL) !!\n");
894 * Truncate (delete every record)
896 void cdb_trunc(int cdb)
904 "cdb_trunc must not be called in a transaction.\n");
907 bailIfCursor(MYCURSORS,
908 "attempt to write during r/o cursor");
913 if ((ret = dbp[cdb]->truncate(dbp[cdb], /* db */
914 NULL, /* transaction ID */
915 &count, /* #rows deleted */
917 if (ret == DB_LOCK_DEADLOCK) {
922 "cdb_truncate(%d): %s\n", cdb,